在 Ubuntu 下使用 C++ 的 STL(Standard Template Library,标准模板库) 其实和使用普通 C++ 一样,因为 STL 是 C++ 标准的一部分,只要用 g++ 编译即可。
下面从 环境准备 → 基本用法 → 常见 STL 示例 → 编译运行 给你一个完整说明。
sudo apt update
sudo apt install g++ build-essential
g++ --version
STL 主要包括:
vector, list, map, set, unordered_mapsort, find, countvector 使用#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {3, 1, 4, 1, 5};
v.push_back(9);
for (int x : v) {
cout << x << " ";
}
cout << endl;
return 0;
}
g++ test.cpp -o test
./test
map(键值对)#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> m;
m["apple"] = 3;
m["banana"] = 5;
for (auto &p : m) {
cout << p.first << ": " << p.second << endl;
}
}
set(去重有序)#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s = {3, 1, 2, 2, 3};
for (int x : s) {
cout << x << " ";
}
}
unordered_map(哈希表,更快)#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> um;
um["a"] = 1;
um["b"] = 2;
}
sort#include <algorithm>
#include <vector>
vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end());
findauto it = find(v.begin(), v.end(), 9);
if (it != v.end()) {
cout << "found";
}
g++ test.cpp -std=c++17 -o test
vector(最常用)stringmap / unordered_mapsetalgorithm(sort / find)如果你愿意,我可以:
你想从哪一块继续?