3

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?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
eaytan
  • 319
  • 2
  • 3
  • 10

2 Answers2

3

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?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182