Keeping std::vector instances sorted
Arrays and vectors do not sort their payload objects themselves. But if we need that, this does not mean that we always have to switch to data structures, which were designed to do that automatically. If an std::vector
is perfect for our use case, it is still very simple and practical to add items to it in a sorting manner.
How to do it...
In this section, we will fill an std::vector
with random words, sort it, and then insert more words while keeping the vector's sorted word order intact.
- Let's first include all headers we're going to need.
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <cassert>
- We also declare that we are using namespace
std
in order to spare us somestd::
prefixes:
using namespace std;
- Then we write a little main function, which fills a vector with some random strings.
int main() { ...