tuple
c++の多次元のtuple(読み方: タプル)の扱いで苦労したので記載する。
今回はtupleのvectorで多次元タプルを使用。
以下プログラム。
#include <iostream> #include<vector> #include <string> #include <tuple> using namespace std; int main(void){ int n=5; int x[]={1,2,3,4,5}; int y[]={10,50,20,90,5}; string s="ABCDE"; vector <tuple<int,int,int>> p; for(int i=0;i<n;i++){ p.push_back(make_tuple(y[i],x[i],s[i])); } /* tupleの中身 (1,10,A) (2,50,B) (3,20,C) (4,90,D) (5,5,E) */ // 全要素表示 for( auto& element : p ) { cout << get<0>(element) << ", " << get<1>(element) << ", " << get<2>(element) << endl; } cout << endl; // 任意の要素を抽出 // 3番目の2番目の要素を変数に代入 int hoge= get<1>(p[3]); cout<< hoge <<endl; return 0; }
- タプルの表示
タプルの表示方法を2種類記載する。get<何番目の要素>(何番目のtuple)で記載する。
ここで<>の中には変数を入れることができないため、0,1,2...など直接数字を書く必要があるようだ。
// 全要素表示 for( auto& element : p ) { cout << get<0>(element) << ", " << get<1>(element) << ", " << get<2>(element) << endl; } cout << endl;
または
// 全要素表示 for(int i=0;i<n;i++){ cout<< get<0>(p[i])<<" "<< get<1>(p[i])<<" "<< get<2>(p[i]); cout<<endl; }
ちなみに実際に<>の中身を変数としてforで回す以下のプログラムが以下。
for(int i=0;i<n;i++){ for(int j=0;j<3;j++){ cout<< get<j>(p[i])<<" "; } cout<<endl; }
エラーが出る。
error: no matching function for call to 'get' cout<< get<k>(p[i])<<" "; ^~~~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__tuple:226:1: note: candidate template ignored: invalid explicitly-specified argument for template parameter '_Ip' get(array<_Tp, _Size>&) _NOEXCEPT;