开发者

How to get the elements in a set in C++? [duplicate]

This question already has answers he开发者_如何学JAVAre: How to iterate std::set? (5 answers) Closed 5 years ago.

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?


Replace type with, for example, int.. And var with the name of the set

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(type element, var) {
   /* Here you can use var */
}

You can also do #define foreach BOOST_FOREACH so that you can do this:

foreach(type element, var) {
   /* Here you can use var */
}

For example:

foreach(int i, name_of_set) {
   cout << i;
}


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. ;)


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


For C++11 and newer:

std::set<int> my_set;
for (auto item : my_set)
    std::cout << item << endl;


I'm liking what I'm seeing in VS2010 Beta2 using C++0x lambda syntax:

std::for_each( s.begin(), s.end(), 
               [](int value)
               { 
                  // what would be in a function operator() goes here.
                  std::cout << value << std::endl; 
               } );


set<int> os;
for (auto itr  = os.begin(); itr != os.end() ; ++itr) cout << *itr << endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜