Programs & Examples
STL Containers · Study material
Building a word index with map and set
A map from each word to a set of line numbers gives sorted words and sorted, duplicate-free line lists automatically.
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines{
"learn c plus plus",
"plus learn data structures",
"practice c every day",
};
std::map<std::string, std::set<int>> index; // word -> line numbers (sorted, unique)
for (std::size_t i = 0; i < lines.size(); ++i) {
std::istringstream in(lines[i]);
for (std::string w; in >> w; ) index[w].insert(static_cast<int>(i + 1));
}
for (const auto& [word, where] : index) {
if (where.size() < 2) continue; // only words on several lines
std::cout << word << ':';
for (int n : where) std::cout << ' ' << n;
std::cout << '\n';
}
return 0;
}
c: 1 3 learn: 1 2 plus: 1 2
Every sequence container side by side
The first introduction example shows vector, deque, list, forward_list and array performing their typical operations.
Counting words and visited points with hash containers
The unordered example counts word frequencies and tracks visited grid points with a custom hash.