I am learning STL now. I read about set container. I have question when you want to use set? After reading description of set it looks like it is useless because we can substitute it by vector. Could you say pros and cos for vector vs set containers. Thanks
I am learning STL now. I read about set container. I have question when
Share
A
setis ordered. It is guaranteed to remain in a specific ordering, according to a functor that you provide. No matter what elements you add or remove (unless you add a duplicate, which is not allowed in aset), it will always be ordered.A
vectorhas exactly and only the ordering you explicitly give it. Items in avectorare where you put them. If you put them in out of order, then they’re out of order; you now need tosortthe container to put them back in order.Admittedly,
sethas relatively limited use. With proper discipline, one could insert items into avectorand keep it ordered. However, if you are constantly inserting and removing items from the container,vectorwill run into many issues. It will be doing a lot of copying/moving of elements and so forth, since it is effectively just an array.The time it takes to insert an item into a
vectoris proportional to the number of items already in thevector. The time it takes to insert an item into asetis proportional to the log₂ of the number of items. If the number of items is large, that’s a huge difference. log₂(100,000) is ~16; that’s a major speed improvement. The same goes for removal.However, if you do all of your insertions at once, at initialization time, then there’s no problem. You can insert everything into the
vector, sort it (paying that price once), and then use standard algorithms for sortedvectorsto find elements and iterate over the sorted list. And while iteration over the elements of asetisn’t exactly slow, iterating over avectoris faster.So there are cases where a sorted
vectorbeats aset. That being said, you really shouldn’t bother with the expense of this kind of optimization unless you know that it is necessary. So use asetunless you have experience with the kind of system you’re writing (and thus know that you need that performance) or have profiling data in hand that tells you that you need avectorand not aset.