2つの異なる型の値を保持することができるクラス
std::pair<変数型,変数型> p = std::make_pair(値,値);
p.first//最初の要素
p.second//2つ目の要素
2つの異なる型の値を返す関数例
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
#include <string>
std::pair<std::string,int> func()
{
return std::make_pair("A",1);
}
int main()
{
auto p=func();
std::cout << "(" << p.first << "," << p.second << ") " << std::endl;
return 0;
}
vectorを使用した例
#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)
}
}
複数の異なる型の値を保持することができるクラス
std::tuple<変数型,変数型,変数型> t = std::make_tuple(値,値,値);
std::get<0>(t);//0番目の要素
std::get<1>(t);//1番目の要素
std::get<2>(t);//2番目の要素
複数の異なる型の値を返す関数例
#include <iostream>
#include <tuple>
#include <string>
// 関数から複数の値を返す
std::tuple<int, char, std::string> f()
{
// std::make_tuple()はほとんどの状況で必要ない
return {1, 'a', "hello"};
}
int main()
{
// 構造化束縛でタプルを分解して、それぞれの要素を代入
auto [a, b, c] = f();
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
}