Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of vectors in c++

Tags:

c++

set

vector

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] ;
like image 795
JuanPablo Avatar asked Jan 11 '11 03:01

JuanPablo


People also ask

What is a set of vector?

A set is a collection of objects. For example, the set of integers from 1 through 5. A vector space is a set of elements (called vectors) which is defined "over a field" in the sense that if you multiply by a number in the field (think real numbers), you still get an element in the vector space.

What are vectors in C?

Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.

Can I make a set of vectors in C++?

C++ Get the vector. Define a set that copies all elements of the vector using 2 pointers begin and end. Print the set.

What is set in CP?

Sets are a type of associative container in which each element has to be unique because the value of the element identifies it.


2 Answers

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;
like image 73
Dawson Avatar answered Oct 22 '22 20:10

Dawson


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
like image 27
EmeryBerger Avatar answered Oct 22 '22 20:10

EmeryBerger