Common mistakes when misusing container libraries include not using fixed-size containers (1), using iterators out of range (2), using the wrong container type (3), confusing container adapters with underlying containers (4), and Violation of ownership rules (5). Solutions include using list or container adapters, checking iterator validity or using range-based loops, matching container types and their iterators, correctly accessing the underlying container through the container adapter, and following the ownership rules of the container library.
Common misuse and solutions of C++ container library
The container library is an important part of the C++ standard library and is widely used For storing and manipulating data structures. However, beginners often misuse these containers, resulting in hard-to-find errors.
1. Memory overhead is not considered
// 错误:预先分配了比所需更多的空间 vector<int> v(1000000);
Solution: Use only when a fixed size container is required, otherwise use a list or container adapter .
// 正确:根据需要增长 list<int> v;
2. Improper use of iterators
// 错误:在范围外访问 for (auto it = v.begin(); it != v.end(); ++it) { *it += 1; if (it == v.end()) { // 迭代器已无效 break; } }
Solution:Always check the validity of iterators, or use range-based for cycle.
// 正确:基于范围的 for 循环 for (int& x : v) { x += 1; }
3. Using the "wrong" container type
// 错误:对无序容器使用有序迭代器 set<int> s; for (auto it = s.begin(); it != s.end(); ++it) { // 有序迭代器 *it += 1; }
Solution: Match the container type and its iterator type.
// 正确:无序迭代器 for (auto it = s.begin(), ie = s.end(); it != ie; ++it) { *it += 1; }
4. Confusing the container adapter and the base container
// 错误:将容器适配器与基础容器混合使用 map<int, vector<int>> m; m[0].push_back(1); m.find(0)->second.push_back(2); // 错误,返回容器适配器
Solution: Use the correct syntax when accessing the base container through the container adapter.
// 正确:通过容器适配器访问基础容器 m.find(0)->second.emplace_back(2);
5. Violation of ownership rules
// 错误:指针指向已销毁的容器中的元素 { vector<int> v; int* ptr = &v[0]; v.pop_back(); // ptr 指向已销毁的元素 }
Solution: Follow the ownership rules of the container library and ensure that the pointer points to a valid element.
// 正确:使用智能指针或引用 std::shared_ptr<int> ptr = &v[0];
Practical case:
Write a program that reads a set of words from a file and counts their occurrences. Use an unordered map to store words and their counts.
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { // 读取单词并计数出现次数 unordered_map<string, int> word_counts; for (string line; getline(cin, line); ) { for (string word : line | views::split(" ")) { // C++20 范围-视图 word_counts[word]++; } } // 打印出现次数最多的 10 个单词 for (auto [word, count] : word_counts | views::take(10) | views::reverse) { cout << word << ": " << count << '\n'; } }
The above is the detailed content of Common misuses and solutions of C++ container libraries. For more information, please follow other related articles on the PHP Chinese website!