- C++17 STL Cookbook
- Jacek Galowicz
- 316字
- 2025-04-04 19:00:07
How it works...
The whole recipe concentrates on breaking down a large string into sentences of text, which are assessed for their length, and then ordered in a multimap. Because std::multimap itself is so easy to use, the complex part of the program is the loop, which iterates over the sentences:
const auto end_it (end(content));
auto it1 (begin(content)); // (1) Beginning of string
auto it2 (find(it1, end_it, '.')); // (1) First '.' dot
while (it1 != end_it && std::distance(it1, it2) > 0) {
string sentence {it1, it2};
// Do something with the sentence string...
it1 = std::next(it2, 1); // One character past current '.' dot
it2 = find(it1, end_it, '.'); // Next dot, or end of string
}
Let's look at the code with the following diagram in mind, which consists of three sentences:

The it1 and it2 are always moved forward through the string together. This way they always point to the beginning and end of one sentence. The std::find algorithm helps us a lot in that regard because it works like "start at the current position and then return an iterator to the next dot character. If there is none, return the end iterator."
After we extract a sentence string, we determine how many words it contains, so we can insert it into the multimap. We are using the number of words as the key for the map nodes, and the string itself as the payload object associated with it. There can easily be multiple sentences which have the same length. This would render us unable to insert them all into one std::map. But since we use std::multimap, this is no problem, because it can easily handle multiple keys of the same value. It will keep them all ordered in line, which is what we need to enumerate all sentences by their length and output them to the user.