Keep Vector Elements Sorted
Learn to keep vector elements sorted.
We'll cover the following
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 we need. We can, however, keep our 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:
Get hands-on with 1400+ tech skills courses.