Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector to set? [closed]

Tags:

c++

set

vector

I have a vector, in which I save objects. I need to convert it to set. I have been reading about sets, but I still have a couple of questions:

  • How to correctly initialize it? Honestly, some tutorials say it is fine to initialize it like set<ObjectName> something. Others say that you need an iterator there too, like set<Iterator, ObjectName> something.

  • How to insert them correctly. Again, is it enough to just write something.insert(object) and that's all?

  • How to get a specific object (for example, an object which has a named variable in it, which is equal to "ben") from the set?

I have to convert the vector itself to be a set (a.k.a. I have to use a set rather than a vector).

like image 626
Marius Avatar asked Nov 18 '13 16:11

Marius


People also ask

How do you turn a vector into a set?

Get the vector to be converted. Create an empty set, to store the result. Iterate through the vector one by one, and insert each element into the set. Print the resultant set.

How do you store a vector in an unordered set?

An unordered set vector is an unordered associative container that is used to hold unique vectors together. Two vectors are considered the same if the corresponding elements of the vectors are equal. Unlike a set of vectors, vectors are not arranged in any particular order in an unordered set of vectors.


2 Answers

Suppose you have a vector of strings, to convert it to a set you can:

std::vector<std::string> v;  std::set<std::string> s(v.begin(), v.end()); 

For other types, you must have operator< defined.

like image 99
masoud Avatar answered Oct 14 '22 12:10

masoud


All of the answers so far have copied a vector to a set. Since you asked to 'convert' a vector to a set, I'll show a more optimized method which moves each element into a set instead of copying each element:

std::vector<T> v = /*...*/;  std::set<T> s(std::make_move_iterator(v.begin()),               std::make_move_iterator(v.end())); 

Note, you need C++11 support for this.

like image 20
David Avatar answered Oct 14 '22 13:10

David