- C++17 STL Cookbook
- Jacek Galowicz
- 274字
- 2025-04-04 19:00:06
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 some std:: prefixes:
using namespace std;
- Then we write a little main function, which fills a vector with some random strings.
int main()
{
vector<string> v {"some", "random", "words",
"without", "order", "aaa",
"yyy"};
- The next thing we do is sorting that vector. Let's do that with some assertions and the is_sorted function from the STL before, which shows that the vector really was not sorted before, but is sorted afterward.
assert(false == is_sorted(begin(v), end(v)));
sort(begin(v), end(v));
assert(true == is_sorted(begin(v), end(v)));
- Now, we finally add some random words into the sorted vector using a new insert_sorted function, which we still need to implement afterward. These words shall be put at the right spot so that the vector is still sorted afterward:
insert_sorted(v, "foobar");
insert_sorted(v, "zzz");
- So, let's now implement insert_sorted a little earlier in the source file.
void insert_sorted(vector<string> &v, const string &word)
{
const auto insert_pos (lower_bound(begin(v), end(v), word));
v.insert(insert_pos, word);
}
- Now, back in the main function where we stopped, we can now continue printing the vector and see that the insert procedure works:
for (const auto &w : v) {
cout << w << " ";
}
cout << '\n';
}
- Compiling and running the program yields the following nicely sorted output:
aaa foobar order random some without words yyy zzz