C++:C++ std::set と std::pair / std::tuple の解説
C++•セットとタプル

C++ std::set と std::pair / std::tuple の解説

重複のないソート済みコレクション向けの std::set と、関数から複数値を返す std::pair / std::tuple を学びます。

構文

#include <set> #include <tuple> std::set<int> uniqueVals; auto t = std::make_tuple(1, "A", true);

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
std::setContainer一意な要素を自動的にソートして格納します。
std::tupleHeterogeneous Container異なる型を含む固定長コレクション。

そのまま実行できるコード例

Compilra で実行可能

C++ をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

#include <iostream>
#include <set>
#include <tuple>
#include <string>

// Function returning multiple values via tuple
std::tuple<std::string, int, double> getSystemStatus() {
    return {"Worker-01", 8080, 99.4};
}

int main() {
    // 1. std::set: Automatic deduplication and sorting
    std::set<int> uniquePortCodes = {80, 443, 8080, 80, 22, 443};
    std::cout << "Unique Sorted Ports:\n";
    for (int port : uniquePortCodes) {
        std::cout << "  Port: " << port << "\n";
    }

    // 2. Unpacking tuple using C++17 structured binding
    auto [name, port, uptime] = getSystemStatus();
    std::cout << "\nNode Status: " << name << " on port " << port << " (Uptime: " << uptime << "%)\n";

    return 0;
}
期待される出力:
Unique Sorted Ports:
  Port: 22
  Port: 80
  Port: 443
  Port: 8080

Node Status: Worker-01 on port 8080 (Uptime: 99.4%)

動作のしくみ: ステップ解説

  • 7-9 行目: string、int、double の std::tuple を返す関数を定義します。
  • 13 行目: std::set が入力値 80 と 443 の重複を除き昇順に並べ替えます。
  • 20 行目: C++17 構造化束縛によりタプルのフィールドを個別の変数へ展開します。

重要ポイント

  • std::set は重複エントリを防ぎ、O(log n) 操作で要素を整列します。
  • std::unordered_set は O(1) ハッシュテーブルによる集合格納を提供します。
  • C++17 の構造化束縛によりタプルを直感的で読みやすく扱えます。

よくある間違い: 実行時変数を使ってタプル要素にアクセスしようとする

std::get<N>(t) では N がコンパイル時定数整数である必要があります。

❌ 誤り
int i = 0;
std::get<i>(myTuple); // Compile Error! i must be constexpr
✅ 正しい例
std::get<0>(myTuple); // Compile-time index

関連するC++チュートリアルとコンパイラ

Compilra で C++ を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。