I have a vector, in which I save objects. I need to convert it to set. I have been reading about set, 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 specific object (for example object, which has name variable in it, which is equal to "ben") from set?
P.S. I have convert vector it self to be as a set (a.k.a. I have to use set rather then vector). Only set can be in my code.
You haven't told us much about your objects, but suppose you have a class like this:
You want to put some Things into a set, so you try this:
This fails, because sets are sorted, and there's no way to sort Things, because there's no way to compare two of them. You must provide either an
operator<
:or a comparison function object:
To find the Thing whose name is "ben", you can iterate over the set, but it would really help if you told us more specifically what you want to do.
You can initialize a set using the objects in a vector in the following manner:
This is the easy part. Now, you have to realize that in order to have elements stored in a set, you need to have
bool operator<(const T&a, const T& b)
operator overloaded. Also in a set you can have no more then one element with a given value acording to the operator definition. So in the sets
you can not have two elements for which neitheroperator<(a,b)
noroperator<(b,a)
is true. As long as you know and realize that you should be good to go.All of the answers so far have copied a
vector
to aset
. Since you asked to 'convert' avector
to aset
, I'll show a more optimized method which moves each element into aset
instead of copying each element:Note, you need C++11 support for this.
If all you want to do is store the elements you already have in a vector, in a set:
Creating a set is just like creating a vector. Where you have
(or some other type rather than
int
) replace it withTo add elements to the set, use
insert
:Suppose you have a vector of strings, to convert it to a set you can:
For other types, you must have
operator<
defined.