1

I'm going to have around 1000 strings that need to be sorted alphabetically.

std::set, from what I've read, is sorted. std::vector is not. std::set seems to be a simpler solution, but if I were to use a std::vector, all I would need to do is use is std::sort to alphabetize the strings.

My application may or may not be performance critical, so performance isn't necessarily the issue here (yet), but since I'll need to iterate through the container to write the strings to the file, I've read that iterating through a std::set is a tad bit slower than iterating through a std::vector.

I know it probably won't matter, but I'd like to hear which one you all would go with in this situation.

Which stl container would best suit my needs? Thanks.

Noah Roth
  • 9,060
  • 5
  • 19
  • 25
  • How often do you need to perform sorts? – Oliver Charlesworth Feb 23 '13 at 00:22
  • I only need to sort once when all the strings are added to the container. – Noah Roth Feb 23 '13 at 00:32
  • possible duplicate of [In which scenario do I use a particular STL Container?](http://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container) – Bartek Banachewicz Feb 23 '13 at 00:33
  • possible duplicate of [How can I efficiently select a Standard Library container in C++11?](http://stackoverflow.com/questions/10699265/how-can-i-efficiently-select-a-standard-library-container-in-c11) – Xeo Feb 23 '13 at 00:34

1 Answers1

2

std::vector with a one-time call to std::sort seems like the simplest way to do what you are after, computationally speaking. std::set provides dynamic lookups by key, which you don't really need here, and things will get more complicated if you have to deal with duplicates.

Make sure you use reserve to pre-allocate the memory for the vector, since you know the size ahead of time in this case. This prevents memory reallocation as you add to the vector (very expensive).

Also, if you use [] notation instead of push_back() you may save a little time avoiding bounds checking of push_back(), but that is really academic and insubstantial and perhaps not even true with compiler optimizations. :-)

moodboom
  • 6,225
  • 2
  • 41
  • 45
  • Excellent points. To which I'd add It's also worth mentioning that library implementations like GNU `libstdc++` often offer switchable "debug modes" including bounds-checked container `operator[]`s, letting us forego `.at()` but retain an easier, release-transparent, `assert`-like ability to check bounds in debugging. This is (or will be, once I refactor) great for me: usually I know the bounds are fixed but just want to make sure I'm not doing daft things. It'll avoid a monstrous `s/\.at(\(\w*\)/[\1]/g` or worse later! – underscore_d Feb 14 '16 at 04:50