Keep vector elements sorted
The vector
is a sequential container that keeps elements in the order in which they were inserted. It does not sort elements, nor change their order in any way. Other containers, such as set
and map
, keep elements sorted, but those containers are not random-access and may not have the features you need. You can, however, keep your vector sorted. It just requires a little bit of management.
How to do it…
The idea with this recipe is to create a simple function, insert_sorted()
, that inserts an element into the correct position in a vector to keep the vector sorted.
- For convenience, we'll start with a type alias for a vector of strings:
using Vstr = std::vector<std::string>;
I like a type alias here because the exact details of the vector are not so important as its application.
- Then we can define a couple of support functions:
// print a vector void printv(const auto& v) { for(const...