C++
std :: pair
サーチ…
ペアの作成と要素へのアクセス
ペアでは、2つのオブジェクトを1つのオブジェクトとして扱うことができます。ペアはテンプレート関数std::make_pair助けを借りて簡単に構築できます。
もう1つの方法は、ペアを作成して後でその要素( firstとsecond )を割り当てることです。
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> p = std::make_pair(1,2); //Creating the pair
std::cout << p.first << " " << p.second << std::endl; //Accessing the elements
//We can also create a pair and assign the elements later
std::pair<int,int> p1;
p1.first = 3;
p1.second = 4;
std::cout << p1.first << " " << p1.second << std::endl;
//We can also create a pair using a constructor
std::pair<int,int> p2 = std::pair<int,int>(5, 6);
std::cout << p2.first << " " << p2.second << std::endl;
return 0;
}
オペレータの比較
これらの演算子のパラメータはlhsとrhs
-
operator==lhsとrhs両方の要素が等しいかどうかをrhsます。戻り値は、lhs.first == rhs.firstとlhs.second == rhs.second両方がtrue場合はtrue、そうでない場合はfalse
std::pair<int, int> p1 = std::make_pair(1, 2);
std::pair<int, int> p2 = std::make_pair(2, 2);
if (p1 == p2)
std::cout << "equals";
else
std::cout << "not equal"//statement will show this, because they are not identical
operator!=lhsとrhsペアの要素が等しくないかどうかを調べます。lhs.first != rhs.firstまたはlhs.second != rhs.secondいずれかでtrue場合、戻り値はtrueです。それ以外の場合はfalse返しfalse。operator<lhs.first<rhs.first場合はtrue返しtrue。それ以外の場合、rhs.first<lhs.firstがfalse返す場合それ以外の場合は、lhs.second<rhs.secondがtrue返し、そうでない場合はfalse返しfalse。operator<=returns!(rhs<lhs)operator>はrhs<lhs返します。operator>=returns!(lhs<rhs)ペアのコンテナを使用した別の例これは、コンテナをソートする必要があるため、
operator<使用します。
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
#include <string>
int main()
{
std::vector<std::pair<int, std::string>> v = { {2, "baz"},
{2, "bar"},
{1, "foo"} };
std::sort(v.begin(), v.end());
for(const auto& p: v) {
std::cout << "(" << p.first << "," << p.second << ") ";
//output: (1,foo) (2,bar) (2,baz)
}
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow