c++data-structuresstdvectorstdmapstdset

Storing in std::map/std::set vs sorting a vector after storing all data



Solution

  • It depends on the situation.

    map and set are usually red-black trees, they should do a lot of work to be balanced, or the operation on it will be very slow. And it doesn't support random access. so if you only want to sort one time, you shouldn't use them.

    However, if you want to continue insert elements into the container and keep order, map and set will take O(logN) time, while the sorted vector is O(N). The latter is much slower, so if you want frequently insert and delete, you should use map or set.