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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With