C++ 中的向量集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4653836/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:03:11 来源:igfitidea点击:
Set of vectors in c++
提问by JuanPablo
How I can get the elements in the vectors set? This is the code I have :
如何获取向量集中的元素?这是我的代码:
std::set< std::vector<int> > conjunto;
std::vector<int> v0 = std::vector<int>(3);
v0[0]=0;
v0[1]=10;
v0[2]=20;
std::cout << v0[0];
conjunto.insert(v0);
v0[0]=1;
v0[1]=11;
v0[2]=22;
conjunto.insert(v0);
std::set< std::vector<int> >::iterator it;
std::cout << conjunto.size();
for( it = conjunto.begin(); it != conjunto.end(); it++)
std::cout << *it[0] ;
采纳答案by EmeryBerger
You're close. You need to pull the vector out of the set iterator. See below.
你很接近。您需要将向量从集合迭代器中取出。见下文。
main()
{
std::set< std::vector<int> > conjunto;
std::vector<int> v0 = std::vector<int>(3);
v0[0]=0;
v0[1]=10;
v0[2]=20;
std::cout << v0[0] << endl;
conjunto.insert(v0);
v0[0]=1;
v0[1]=11;
v0[2]=22;
conjunto.insert(v0);
std::set< std::vector<int> >::iterator it;
std::cout << "size = " << conjunto.size() << endl;
for( it = conjunto.begin(); it != conjunto.end(); it++) {
const std::vector<int>& i = (*it); // HERE we get the vector
std::cout << i[0] << endl; // NOW we output the first item.
}
Output:
输出:
$ ./a.out
0
size = 2
0
1
回答by Dawson
The []
operator takes precedence over the *
operator, so you want to change the for
loop to:
该[]
运营商优先于*
运营商,所以你要改变for
回路:
for (it = conjunto.begin(); it != conjunto.end(); it++)
std::cout << (*it)[0] << std::endl;
回答by Pavel
Now, with C++11 standart, it's easier:
现在,有了 C++11 标准,就更容易了:
set< vector<int> > conjunto;
// filling conjunto ...
for (vector<int>& v: conjunto)
cout << v[0] << endl;
回答by vdsf
std::set<std::vector<int> >::const_iterator it = cunjunto.begin();
std::set<std::vector<int> >::const_iterator itEnd = conjunto.end();
for(; it != itEnd; ++it)
{
// Here *it references the element in the set (vector)
// Therefore, declare iterators to loop the vector and print it's elements.
std::vector<int>::const_iterator it2 = (*it).begin();
std::vector<int>::const_iterator it2End = (*it).end();
for (; it2 != it2End; ++it2)
std::cout << *it2;
}