阅读量:3
在Linux中使用C++ STL(Standard Template Library)容器非常简单。首先,确保你的编译器支持C++11或更高版本。然后,在你的代码中包含所需的头文件,并使用相应的容器类。下面是一些常用的STL容器及其用法:
- 向量(vector)
#include
#include
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 添加元素
vec.push_back(6);
// 访问元素
std::cout << "Element at index 2: " << vec[2] << std::endl;
// 遍历向量
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
- 列表(list)
#include
#include
int main() {
std::list<int> lst = {1, 2, 3, 4, 5};
// 添加元素
lst.push_back(6);
// 访问元素
auto it = lst.begin();
std::advance(it, 2);
std::cout << "Element at index 2: " << *it << std::endl;
// 遍历列表
for (int num : lst) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
- 双端队列(deque)
#include
#include
int main() {
std::deque<int> deq = {1, 2, 3, 4, 5};
// 添加元素
deq.push_back(6);
deq.push_front(0);
// 访问元素
std::cout << "Element at index 2: " << deq[2] << std::endl;
// 遍历双端队列
for (int num : deq) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
- 集合(set)
#include
#include
int main() {
std::set<int> st = {1, 2, 3, 4, 5};
// 添加元素
st.insert(6);
// 访问元素
auto it = st.find(3);
if (it != st.end()) {
std::cout << "Element found: " << *it << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
// 遍历集合
for (int num : st) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
要编译这些示例,请使用以下命令:
g++ -std=c++11 your_file.cpp -o your_output_file
然后运行生成的可执行文件:
./your_output_file
这些示例展示了如何在Linux中使用C++ STL容器。你可以根据需要选择合适的容器类型,并使用相应的操作。
以上就是关于“C++在Linux中如何使用STL容器”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm