Linux下C++容器技术使用指南
一 环境准备与编译运行
sudo apt-get update && sudo apt-get install -y g++ cmakeg++ -std=c++17 -O2 main.cpp -o app./app二 常用容器与典型用法
push_back/emplace_back、at[]/operator[]、front/back、insert/erase、size/capacity/reserve/resize。#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
#include <queue>
int main() {
// vector
std::vector<int> v = {1,2,3};
v.push_back(4);
std::cout << "v[2]=" << v[2] << ", size=" << v.size() << '\n';
// unordered_map
std::unordered_map<std::string, int> m{{"a",1},{"b",2}};
m["c"] = 3;
if (m.find("b") != m.end()) std::cout << "b=" << m["b"] << '\n';
// set
std::set<int> s{3,1,4};
s.insert(2);
for (int x : s) std::cout << x << ' '; // 1 2 3 4
std::cout << '\n';
// queue
std::queue<int> q;
q.push(10); q.push(20);
std::cout << "front=" << q.front() << '\n';
q.pop();
}
以上容器与接口为 STL 的常见用法,适用于 Linux 环境下的日常开发。三 容器选择与性能要点
四 与STL算法协同与遍历
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {3,1,4,1,5};
std::sort(v.begin(), v.end()); // 排序 O(n log n)
auto it = std::find(v.begin(), v.end(), 4); // 查找
if (it != v.end()) std::cout << "found 4\n";
std::cout << "count(1)=" << std::count(v.begin(), v.end(), 1) << '\n';
}
算法与容器组合是 STL 高效开发的关键实践。五 调试与性能分析工具