温馨提示×

Linux C++中STL算法怎么用

小樊
42
2025-08-16 03:21:16
栏目: 编程语言

在C++的STL(Standard Template Library)中,有许多有用的算法可以用于处理容器中的数据。这些算法通常位于<algorithm>头文件中。以下是一些常用的STL算法及其用法:

  1. sort(): 对容器进行排序。例如,对一个vector进行排序:
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {5, 3, 1, 4, 2};
    std::sort(vec.begin(), vec.end());

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}
  1. find(): 在容器中查找指定元素。例如,在一个vector中查找元素:
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int target = 3;

    auto it = std::find(vec.begin(), vec.end(), target);

    if (it != vec.end()) {
        std::cout << "Element found at position: " << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "Element not found" << std::endl;
    }

    return 0;
}
  1. count(): 计算容器中某个元素的出现次数。例如,在一个vector中计算元素出现的次数:
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 2, 1, 3, 1, 1, 2, 3, 3, 3};
    int target = 3;

    int count = std::count(vec.begin(), vec.end(), target);

    std::cout << "Element " << target << " appears " << count << " times" << std::endl;

    return 0;
}
  1. transform(): 对容器中的每个元素执行指定操作。例如,将一个vector中的所有元素乘以2:
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::vector<int> result(vec.size());

    std::transform(vec.begin(), vec.end(), result.begin(), [](int x) { return x * 2; });

    for (int num : result) {
        std::cout << num << " ";
    }

    return 0;
}

这只是STL算法的一部分。还有许多其他算法,如reverse()unique()merge()等。要了解更多关于STL算法的信息,请查阅C++官方文档或相关教程。

0