std::map is an associative container that stores sorted std::pair<const Key, Value> elements. Keys are unique and maintained in sorted order via Red-Black trees.
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"apple", "banana", "apple", "cherry", "banana", "apple"};
std::map<std::string, int> frequency;
for (const auto& w : words) {
frequency[w]++;
}
std::cout << "--- Word Frequencies (Sorted Alphabetically) ---\n";
// Modern C++17 Structured Binding:
for (const auto& [word, count] : frequency) {
std::cout << word << ": " << count << "\n";
}
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Compare O(log N) tree maps with O(1) hash maps.
Sorted keys without associated values.
Unpacking key-value pairs with auto [k, v].