What is the difference between std::set and std::vector?

前端 未结 5 1735
南笙
南笙 2020-12-02 05:04

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 u

5条回答
  •  春和景丽
    2020-12-02 05:33

    They are different things: you decide how vectors are ordered, and you can also put as many equal things into a vector as you please. Sets are ordered in accordance to that set's internal rules (you may set the rules, but the set will deal with the ordering), and you cannot put multiple equal items into a set.

    Of course you could maintain a vector of unique items, but your performance would suffer a lot when you do set-oriented operations. For example, assume that you have a set of 10000 items and a vector of 10000 distinct unordered items. Now suppose that you need to check if a value X is among the values in the set (or among the values in the vector). When X is not among the items, searching the vector would be some 100 times slower. You would see similar performance differences on calculating set unions and intersections.

    To summarize, sets and vectors have different purposes. You can use a vector instead of a set, but it would require more work, and would likely hurt the performance rather severely.

提交回复
热议问题