STL(Standard Template Library)是C++标准库的核心组成部分,提供了丰富的容器、算法和迭代器等工具。在Linux环境下使用STL进行C++编程非常普遍且高效。
#include <vector>
#include <list>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
// 常用容器示例
std::vector<int> vec = {1, 2, 3}; // 动态数组
std::list<double> lst = {1.1, 2.2}; // 双向链表
std::map<std::string, int> m = {{"a",1}, {"b",2}}; // 有序键值对
#include <algorithm>
std::vector<int> v = {3, 1, 4, 1, 5, 9};
// 排序
std::sort(v.begin(), v.end());
// 查找
auto it = std::find(v.begin(), v.end(), 4);
// 遍历操作
std::for_each(v.begin(), v.end(), [](int x) {
std::cout << x << " ";
});
// 各种迭代器使用
for(auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
// 反向迭代器
for(auto rit = v.rbegin(); rit != v.rend(); ++rit) {
std::cout << *rit << " ";
}
# 使用g++编译STL程序的基本命令
g++ -std=c++17 -O2 -Wall -pedantic your_program.cpp -o program
# 常用选项说明:
# -std=c++17: 指定C++标准版本(也可用c++11/c++14/c++20)
# -O2: 优化级别
# -Wall: 显示所有警告
# -pedantic: 严格要求符合标准
reserve()
预分配内存减少vector的重新分配unordered_map
替代map
std::vector<int> v;
v.reserve(1000); // 预分配空间
pthread_mutex
或C++11的std::mutex
#include <mutex>
std::mutex mtx;
std::vector<int> shared_vec;
void thread_func() {
std::lock_guard<std::mutex> lock(mtx);
shared_vec.push_back(42);
}
#include <fstream>
#include <string>
#include <vector>
// 读取文件到vector
std::vector<std::string> read_lines(const std::string& filename) {
std::vector<std::string> lines;
std::ifstream file(filename);
std::string line;
while(std::getline(file, line)) {
lines.push_back(line);
}
return lines;
}
#include <sys/utsname.h>
#include <vector>
#include <sstream>
std::vector<std::string> get_system_info() {
struct utsname info;
uname(&info);
return {
info.sysname,
info.nodename,
info.release,
info.version,
info.machine
};
}
#include <cstdlib>
#include <vector>
#include <string>
int execute_command(const std::vector<std::string>& args) {
std::vector<char*> argv;
for (const auto& arg : args) {
argv.push_back(const_cast<char*>(arg.c_str()));
}
argv.push_back(nullptr);
return execvp(argv[0], argv.data());
}
#include <memory>
#include <vector>
template <typename T>
class MyAllocator {
// 自定义分配器实现
};
std::vector<int, MyAllocator<int>> custom_vec;
std::vector<std::string> create_strings() {
std::vector<std::string> v;
v.push_back("large string 1");
v.push_back("large string 2");
return v; // 使用移动语义而非拷贝
}
auto strings = create_strings(); // 高效转移所有权
#include <execution>
#include <algorithm>
std::vector<int> v = {...};
// 并行排序
std::sort(std::execution::par, v.begin(), v.end());
// 并行遍历
std::for_each(std::execution::par, v.begin(), v.end(), [](auto& x) {
x.process();
});
# 在gdb中打印STL容器内容
(gdb) p vec
(gdb) p *vec._M_impl._M_start@vec.size()
# 需要安装python pretty-printers
valgrind --leak-check=full ./your_program
# 使用perf分析STL性能
perf record ./your_program
perf report
STL是Linux C++开发中不可或缺的工具,熟练掌握它能大幅提高开发效率和代码质量。