I am using the below code for conversion:
std::set<ObjectType> s(v.begin(), v.end());
However, I need to keep the order of the vector elements. How can I do this?
I am using the below code for conversion:
std::set<ObjectType> s(v.begin(), v.end());
However, I need to keep the order of the vector elements. How can I do this?
You can't if the vector is not ordered. A std::set
keeps it contents in either an ascending or descending order.
If the vector is ordered then you just need to set the comparison function of the std::set
to whatever was used to order the vector.
You may want to see: How to remove duplicates from unsorted std::vector while keeping the original ordering using algorithms?
You can do this if and only if your vector
is sorted by some strict weak ordering, e.g. sorted by <
for numbers. In that case, give the set
the appropriate comparison object (the one you used to sort your vector
) and the order will fit.
Otherwise, if your vector
was not sorted by a fitting criterion, you cannot make the set
keep the original order as sorting the elements is one of the invariants of the set
.