简体   繁体   中英

C++ printing a list of sets

I'm trying to print out a list of sets but I'm confused with the syntax. I want each set to be on a new line. Here is my code:

set<int> set1 = { 2, 4, 5 };
set<int> set2 = { 4, 5 };

list<set<int>> list1;
list<set<int>>::iterator it = list1.begin();

list1.insert(it, set1);
list1.insert(it, set2);

cout << "List contents:" << endl;
for (it = list1.begin(); it != list1.end(); ++it)
{
    cout << *it; //error is here
}

I'm getting an error when trying to print the pointer to the iterator. Pretty sure its because I'm using a set inside of the list, but I don't know the proper syntax for outputting this list.

Do you want to print as following?

  for (it = list1.begin(); it != list1.end(); ++it)
  {
      for (set<int>::iterator s = it->begin(); s != it->end(); s++) {                                                        
          cout << *s << ' ';
      }
      cout << endl;
  }

output:

List contents:
2 4 5
4 5

There is no overload of operator << for std::set , you have to write the loop yourself (and possibly creating a function for that)

With for range, you may simply do:

for (const auto& s : list1) {
    for (int i : s) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM