pair
これは C++ 標準ライブラリのテンプレート クラスで、2 つのオブジェクトの組み合わせを格納するために使用されます。<utility>
これはヘッダー ファイル内にあります。
pair
クラスは次のように定義されます。
template <class T1, class T2>
struct pair {
T1 first;
T2 second;
pair();
pair(const T1& x, const T2& y);
template<class U, class V>
pair(U&& x, V&& y);
template<class U, class V>
pair(const pair<U, V>& p);
template<class U, class V>
pair(pair<U, V>&& p) noexcept;
pair(const pair& p) = default;
pair(pair&& p) noexcept = default;
}
pair
このクラスには 2 つのパブリック メンバー変数 と がありfirst
、second
それぞれ 2 つのオブジェクトを格納するために使用されます。メンバー変数の型は、組み込み型、カスタム型、ポインター型などを含む任意の型にすることができます。
pair
このクラスを使用したサンプルコードは次のとおりです。
#include <iostream>
#include <utility>
int main() {
std::pair<std::string, int> myPair("apple", 3);
std::cout << "Fruit: " << myPair.first << std::endl;
std::cout << "Count: " << myPair.second << std::endl;
return 0;
}
上の例では、メンバーが文字列「apple」で、メンバーが整数 3 であるpair
オブジェクトを作成しました。次に、演算子を使用してオブジェクトとメンバーにアクセスし、出力します。myPair
first
second
.
myPair
first
second
出力例:
Fruit: apple
Count: 3
要約すると、pair
クラスは 2 つのオブジェクトを結合するための便利なツールであり、C++ のさまざまなアプリケーション シナリオで使用できます。