Alex Rivera | Logout

STL + Ordered set + without duplicates

Asked 2010-12-16T16:54:25.170
13

I need to have an ordered set of values without duplicates. So, what is the fast/best method :

1 - Create a vector, sort it and remove duplicates ? 2 - Use a kind of "sorted" vector (if it exists) ?

Which one can be the more efficient ?

Edit
Report

3 Answers

5

Use std::set. It's ordered, and it does not allow duplicates.

The only downside is that you don't get random access to the elements though this was not specified as a requirement.

answered 2010-12-16T16:59:03.173
1

There is always Loki::AssocVector

Otherwise you can easily roll your own:

  • use a std::vector or std::deque as the base container
  • use lower_bound / upper_bound / equal_range and binary_search generic algorithms to look up an object
  • also inplace_merge is great when you already know that the value is not present

But really, use a std::set :)

answered 2010-12-16T18:12:05.287
0

Insert into a set takes log(n). And the sort is free.

Insert into a vector (push_back) takes constant time. Sorting a vector takes n*log(n). But you still need to remove duplicates.

If you insert in one go and then sort, you can consider also vector. If you insert frequently set is the right one.

answered 2010-12-16T17:27:33.770

Your Answer