C++中元组的向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40188779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vector of Tuples in C++
提问by Shailendra Gupta
I have tried every thing which i could but this code is giving me errors. Both syntax are not working. I have commented operator[] but please provide a solution for that as well.
我已经尝试了所有我能做的事情,但是这段代码给了我错误。两种语法都不起作用。我已经评论了 operator[] 但也请提供一个解决方案。
#include <bits/stdc++.h>
using namespace std;
int main() {
typedef vector< tuple<int, int, int> > my_tuple;
my_tuple tl;
tl.push_back( tuple<int, int, int>(21,20,19) );
for (my_tuple::const_iterator i = tl.begin(); i != tl.end(); ++i) {
//cout << get<0>(tl[i]);
//cout << get<0>(tl[i]);
//cout << get<0>(tl[i]);
cout << get<0>(tl.at(i));
cout << get<1>(tl.at(i));
cout << get<2>(tl.at(i));
}
return 0;
}
while printing tuple in for loop i am getting error.
在 for 循环中打印元组时出现错误。
error: no matching function for call to 'std::vector<std::tuple<int, int, int> >::at(std::vector<std::tuple<int, int, int> >::const_iterator&)'
and for operator[ ]
和操作员[]
error: no match for 'operator[]' (operand types are 'my_tuple {aka std::vector<std::tuple<int, int, int> >}' and 'std::vector<std::tuple<int, int, int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const std::tuple<int, int, int>*, std::vector<std::tuple<int, int, int> > >}')
回答by Jana
#include <bits/stdc++.h>
using namespace std;
int main() {
typedef vector< tuple<int, int, int> > my_tuple;
my_tuple tl;
tl.push_back( tuple<int, int, int>(21,20,19) );
for (my_tuple::const_iterator i = tl.begin(); i != tl.end(); ++i) {
cout << get<0>(*i) << endl;
cout << get<1>(*i) << endl;
cout << get<2>(*i) << endl;
}
cout << get<0>(tl[0]) << endl;
cout << get<1>(tl[0]) << endl;
cout << get<2>(tl[0]) << endl;
return 0;
}
回答by John Zwinck
Your i
is an iterator, which is sort of like a pointer, so you need to dereference it, not pass it to operator []
or at()
:
你i
是一个迭代器,有点像一个指针,所以你需要取消引用它,而不是将它传递给operator []
or at()
:
get<0>(*i);
回答by user8518061
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int,string,int>> vt;
vt.push_back({421,"cha",10});
vt.push_back({464,"sam",20});
vt.push_back({294,"sac",30});
for(const auto &i : vt)
cout<<get<0>(i)<<" "<<get<1>(i)<<" "<<get<2>(i)<<endl;
return 0;
}