linux

C++在Linux中如何使用STL容器

小樊
42
2025-06-25 22:46:07
栏目: 编程语言

在Linux中使用C++ STL(Standard Template Library)容器非常简单。首先,确保你的编译器支持C++11或更高版本。然后,在你的代码中包含所需的头文件,并使用相应的容器类。下面是一些常用的STL容器及其用法:

  1. 向量(vector)
#include <iostream>
#include <vector>

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;
}
  1. 列表(list)
#include <iostream>
#include <list>

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;
}
  1. 双端队列(deque)
#include <iostream>
#include <deque>

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;
}
  1. 集合(set)
#include <iostream>
#include <set>

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容器。你可以根据需要选择合适的容器类型,并使用相应的操作。

0
看了该问题的人还看了