0

I have the following code:

set< vector<int> > set_of_things;
vector<int> triplet(3);

//set_of_things.push_back(stuff) - adding a number of things to the set

How do I now iterate through the set and print all elements?

The set is a collection of triplets so the output should look like:

1 2 3 
3 4 5
4 5 6
roshanvid
  • 793
  • 6
  • 21

2 Answers2

5

This is straight-forward with the new range-based for loops that were introduced in C++11:

for (auto const & v : set_of_things)
{
    for (auto it = v.cbegin(), e = v.cend(); it != e; ++it)
    {
        if (it != v.cbegin()) std::cout << " ";
        std::cout << *it;
    }
    std::cout << "\n";
}

If you don't mind a trailing space:

for (auto const & v : set_of_things)
{
    for (auto const & x : v)
    {
        std::cout << *it << " ";
    }
    std::cout << "\n";
}

Or use the pretty printer:

#include <prettyprint.hpp>
#include <iostream>

std::cout << set_of_things << std::endl;

If you have an older compiler, you will have to spell both iterations out in terms of iterators.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 3
    @Jon: Or perhaps the "legacy-C++" requirement should be explicit in the question? :-) – Kerrek SB Sep 05 '12 at 08:19
  • 2
    Point taken, but when the goal is to provide correct, practical and educational solutions then IMHO the onus is on the more knowledgeable party. :-) – Jon Sep 05 '12 at 08:21
1

You use iterators:

for ( std::set<vector<int> >::iterator it = set_of_things.begin() ; 
      it != set_of_things.end() ; 
      it++ )
{
   // *it is a `vector<int>`
}

In C++11 you can use auto instead of std::set<vector<int> >::iterator.

If you're not modifying the iterator, you should use a const_iterator instead.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625