A set ordered. It is guaranteed that he will remain in a certain order, according to the functor you provided. No matter what elements you add or remove (unless you add a duplicate that is not allowed in set ), it will always be ordered.
A vector has exactly and only the order that you explicitly give it. The elements in vector are where you put them. If you expose them to a non-working state, then they are not in order; now you need a sort container to get them back in order.
Admittedly, set has relatively limited use. With the right discipline, you can insert elements into vector and keep them ordered. However, if you constantly insert and remove elements from the container, vector will work in many problems. It will copy / move elements a lot, etc., since it is actually just an array.
The time required to insert an element in vector is proportional to the number of elements already in vector . The time taken to insert an element into a set element is proportional to the logβ of the number of elements. If the number of items is large, this is a huge difference. logβ (100 000) - ~ 16; which is a significant improvement in speed. The same goes for deletion.
However, if you do all your inserts at once, during initialization, then there is no problem. You can insert everything in vector , sort it (by paying this price once), and then use the standard algorithms for sorted vectors to search for items and repeat through the sorted list. And while iterating over the elements of a set not too slow, iterating over vector is faster.
So, there are times when a sorted vector superior to a set . In this case, you really should not worry about the costs of such optimization, if you do not know what it is necessary. Therefore, use set if you do not have experience with the system you are writing (and therefore know that you need this performance) or you have profiling data that tells you that you need vector , not set .
Nicol Bolas Dec 31 '11 at 6:49 2011-12-31 06:49
source share