溫馨提示×

Linux C++中STL算法怎么用

小樊
40
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女