JuanPablo
JuanPablo

Reputation: 24764

Set of vectors in c++

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] ;

Upvotes: 9

Views: 33019

Answers (4)

Pavel
Pavel

Reputation: 5876

Now, with C++11 standart, it's easier:

set< vector<int> > conjunto;
// filling conjunto ...
for (vector<int>& v: conjunto)
    cout << v[0] << endl;

Upvotes: 3

vdsf
vdsf

Reputation: 1618

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;
}

Upvotes: 1

Dawson
Dawson

Reputation: 2771

The [] operator takes precedence over the * operator, so you want to change the for loop to:

for (it = conjunto.begin(); it != conjunto.end(); it++)
    std::cout << (*it)[0] << std::endl;

Upvotes: 9

EmeryBerger
EmeryBerger

Reputation: 3966

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

Upvotes: 4

Related Questions