C++ 如何在C++中获取集合中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1954718/
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
How to get the elements in a set in C++?
提问by SuperString
I am confused as to how to get the elements in the set. I think I have to use the iterator but how do I step through it?
我对如何获取集合中的元素感到困惑。我想我必须使用迭代器,但我如何逐步完成它?
回答by Thomas Bonini
Replace type
with, for example, int
.. And var
with the name of the set
type
例如,替换为int
.. 并替换为var
集合的名称
for (set<type>::iterator i = var.begin(); i != var.end(); i++) {
type element = *i;
}
The best way though is to use boost::foreach. The code above would simply become:
最好的方法是使用boost::foreach。上面的代码将简单地变成:
BOOST_FOREACH(type element, var) {
/* Here you can use var */
}
You can also do #define foreach BOOST_FOREACH
so that you can do this:
您也#define foreach BOOST_FOREACH
可以这样做:
foreach(type element, var) {
/* Here you can use var */
}
For example:
例如:
foreach(int i, name_of_set) {
cout << i;
}
回答by Georg Fritzsche
Use iterators:
使用迭代器:
std::set<int> si;
/* ... */
for(std::set<int>::iterator it=si.begin(); it!=si.end(); ++it)
std::cout << *it << std::endl;
Note that many references like MSDN and cplusplus.com provides examples - one example. ;)
请注意,许多参考资料(如 MSDN 和 cplusplus.com)都提供了示例 -一个示例。;)
回答by codaddict
To list all the elements in the set you can do something like:
要列出集合中的所有元素,您可以执行以下操作:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
int myints[] = {1,2,3,4,5};
set<int> myset (myints,myints+5);
set<int>::iterator it;
cout << "myset contains:";
for ( it=myset.begin() ; it != myset.end(); it++ )
cout << " " << *it;
cout << endl;
return 0;
}
To check if a specific elements in the set or not you can use the find() method from the set STL class
要检查集合中是否有特定元素,您可以使用集合 STL 类中的 find() 方法
回答by paxos1977
I'm liking what I'm seeing in VS2010 Beta2 using C++0x lambda syntax:
我喜欢使用 C++0x lambda 语法在 VS2010 Beta2 中看到的内容:
std::for_each( s.begin(), s.end(),
[](int value)
{
// what would be in a function operator() goes here.
std::cout << value << std::endl;
} );
回答by tvorez
For C++11 and newer:
对于 C++11 及更新版本:
std::set<int> my_set;
for (auto item : my_set)
std::cout << item << endl;
回答by skpro19
set<int> os;
for (auto itr = os.begin(); itr != os.end() ; ++itr) cout << *itr << endl;