centos

CentOS C++STL容器使用技巧

小樊
36
2025-12-27 08:23:25
栏目: 编程语言

CentOS 下 C++ STL 容器使用技巧

一 容器选型与复杂度要点

二 性能优化与常见坑

三 代码示例

#include <vector>
#include <string>

std::vector<std::string> names;
names.reserve(1000);                 // 预分配,避免多次扩容
for (int i = 0; i < 1000; ++i) {
    names.emplace_back("user");       // 原地构造,减少拷贝
}
#include <vector>
#include <algorithm>

std::vector<int> v = {1,2,3,2,4,2,5};
// 删除所有等于 2 的元素
v.erase(std::remove(v.begin(), v.end(), 2), v.end());
#include <map>
#include <iostream>

std::map<int, std::string> m = {{1,"a"},{3,"c"},{5,"e"}};
auto lb = m.lower_bound(3);  // >= 3 的第一个元素
auto ub = m.upper_bound(4);  // >  4 的第一个元素
for (auto it = lb; it != ub; ++it) {
    std::cout << it->first << "=" << it->second << "\n";
}
#include <vector>
#include <cstdio>

std::vector<int> data = {1,2,3,4,5};
if (!data.empty()) {
    std::printf("data: %p, size: %zu\n", static_cast<void*>(&data[0]), data.size());
}

四 多线程与 CentOS 实践建议

0
看了该问题的人还看了