Mastering C++ STL: Vectors, Maps, and Sort with Real-World Examples
This tutorial explains the core components of the C++ Standard Template Library—vector, map, and sort—showing their basic usage, generic capabilities, and how they can be combined in practical code examples such as product sorting and a word‑frequency counter.
In previous lessons we explored C++ template mechanisms, the foundation of generic programming, and introduced the Standard Template Library (STL) as the most powerful realization of those ideas.
This article focuses on three core STL components: the most commonly used containers vector and map, and the powerful algorithm sort, demonstrating how to combine them through concrete examples.
1. Sequence container: std::vector
std::vectoris a dynamic array, a typical sequential container that automatically manages memory, can grow or shrink at runtime, and provides fast random access to its elements.
1.1 Basic usage
#include <iostream>
#include <vector> // 必须包含 vector 头文件
int main() {
// 1. 定义一个存储 int 的 vector
std::vector<int> myVector;
// 2. 向尾部添加元素 (动态扩容)
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
// 3. 像数组一样通过下标访问元素
std::cout << "First element: " << myVector[0] << std::endl; // 输出 10
// 4. 使用 at() 访问,会进行边界检查,更安全
std::cout << "Second element: " << myVector.at(1) << std::endl; // 输出 20
// 5. 获取大小和容量
std::cout << "Size: " << myVector.size() << std::endl; // 当前元素个数:3
std::cout << "Capacity: " << myVector.capacity() << std::endl; // 当前分配的容量
// 6. 范围 for 循环遍历
std::cout << "Vector elements: ";
for (int num : myVector) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}1.2 Power of generics
vectoris a class template, meaning it can hold almost any type. Examples include storing strings, custom structs, and even nested vectors.
#include <vector>
#include <string>
// Store strings
std::vector<std::string> stringVec = {"Hello", "World", "from", "C++"};
// Store custom struct
struct Point { double x, y; };
std::vector<Point> pointsVec = {{1.0, 2.5}, {3.4, 5.6}};
// Store a 2‑D array (vector of vectors)
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};2. Associative container: std::map
std::mapstores unique key‑value pairs, automatically sorted by key (default ascending), and provides fast lookup based on the key.
2.1 Basic usage
#include <iostream>
#include <map> // 必须包含 map 头文件
#include <string>
int main() {
// 1. Define a map from string to int
std::map<std::string, int> studentScores;
// 2. Insert key‑value pairs
studentScores["Alice"] = 95; // using subscript operator
studentScores["Bob"] = 87;
studentScores.insert(std::make_pair("Charlie", 92)); // using insert
// 3. Access elements by key
std::cout << "Alice's score: " << studentScores["Alice"] << std::endl;
// 4. Find an element safely
auto it = studentScores.find("Bob");
if (it != studentScores.end()) {
std::cout << "Found Bob, score: " << it->second << std::endl;
} else {
std::cout << "Bob not found." << std::endl;
}
// 5. Iterate over the map
std::cout << "
All students and scores:" << std::endl;
for (const auto& pair : studentScores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}3. Generic algorithm: std::sort
STL provides many container‑independent algorithms that operate via iterators. std::sort is the most commonly used algorithm for ordering sequences.
3.1 Sorting a vector
#include <iostream>
#include <vector>
#include <algorithm> // 必须包含算法头文件
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
// Default ascending sort
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted (ascending): ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Descending sort using a lambda comparator
std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a > b; });
std::cout << "Sorted (descending): ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}3.2 Combining vector and sort for complex data
Sort a vector of custom Product structs by price.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Product { std::string name; double price; };
int main() {
std::vector<Product> products = {
{"Laptop", 999.99},
{"Mouse", 24.99},
{"Keyboard", 49.99},
{"Monitor", 299.99}
};
// Sort by price (low to high)
std::sort(products.begin(), products.end(), [](const Product& a, const Product& b) {
return a.price < b.price;
});
std::cout << "Products sorted by price (low to high):
";
for (const auto& prod : products) {
std::cout << prod.name << ": $" << prod.price << std::endl;
}
return 0;
}4. Integrated case: Word‑frequency counter
This example combines vector, map, and sort to count how many times each word appears in a text and output the results in descending order of frequency.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <sstream>
#include <cctype>
std::string toLower(const std::string& str) {
std::string result = str;
for (char& c : result) {
c = std::tolower(c);
}
return result;
}
int main() {
std::string text = "C++ is a powerful language. C++ is widely used for system programming. Power and performance are key in C++.";
std::map<std::string, int> wordCount;
std::istringstream iss(text);
std::string word;
while (iss >> word) {
if (!std::isalpha(word.back())) {
word.pop_back(); // remove trailing punctuation
}
word = toLower(word);
wordCount[word]++;
}
// Move map entries to a vector for sorting
std::vector<std::pair<std::string, int>> vec(wordCount.begin(), wordCount.end());
// Sort by frequency descending
std::sort(vec.begin(), vec.end(), [](const std::pair<std::string,int>& a, const std::pair<std::string,int>& b) {
return a.second > b.second;
});
std::cout << "Word Frequency:
";
for (const auto& entry : vec) {
std::cout << entry.first << ": " << entry.second << std::endl;
}
return 0;
}Conclusion
The chapter demonstrates how STL separates data structures from algorithms, dramatically improving code reusability and flexibility. Mastering STL is an essential step toward becoming an efficient C++ programmer.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
