在 Linux 下使用 C++ 的 STL(Standard Template Library),其实和平台关系不大,只要用 支持 C++ 的编译器(如 g++ / clang++) 即可。下面从 环境、基本用法、常见容器与算法、编译方式 几个方面说明。
sudo apt update
sudo apt install g++ # Debian/Ubuntu
查看版本:
g++ --version
vector + sort#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end());
for (int x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
g++ -std=c++11 stl_demo.cpp -o stl_demo
./stl_demo
✅ 推荐开启 C++11 或更高标准
-std=c++11 / c++14 / c++17 / c++20
vector(动态数组)#include <vector>
std::vector<int> v;
v.push_back(10);
v.push_back(20);
v[0] = 100;
常用接口:
push_backsize()empty()clear()begin(), end()map(红黑树,有序)#include <map>
std::map<std::string, int> m;
m["apple"] = 3;
m["banana"] = 5;
for (auto &p : m) {
std::cout << p.first << ": " << p.second << std::endl;
}
unordered_map(哈希表,无序)#include <unordered_map>
std::unordered_map<std::string, int> um;
um["a"] = 1;
set / unordered_set#include <set>
std::set<int> s = {1, 2, 3};
s.insert(4);
string#include <string>
std::string s = "hello";
s += " world";
<algorithm>)#include <algorithm>
| 功能 | 示例 |
|---|---|
| 排序 | std::sort(v.begin(), v.end()) |
| 查找 | std::find(v.begin(), v.end(), x) |
| 最大/最小 | std::max, std::min |
| 遍历 | std::for_each |
示例:
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
std::cout << "found" << std::endl;
}
for (auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
或现代写法:
for (auto &x : v) {
std::cout << x << " ";
}
CXX = g++
CXXFLAGS = -std=c++17 -Wall
all: app
app: main.o
$(CXX) -o app main.o
main.o: main.cpp
$(CXX) $(CXXFLAGS) -c main.cpp
clean:
rm -f *.o app
gdbg++ -g main.cpp -o main
gdb ./main
p v
p m
std::using namespace std; // 不推荐在头文件中使用
vector 插入/删除可能导致迭代器失效map 有序,慢unordered_map 快,无序✅ 推荐顺序:
vectorstringmap / unordered_mapalgorithm如果你愿意,我可以:
你现在是 初学者 / 进阶 / 准备面试?