0
点赞
收藏
分享

微信扫一扫

memcached面试专题及答案

大南瓜鸭 04-07 11:30 阅读 0
c++算法

C++ <algorithm> 头文件是标准库中提供的一系列算法,用于操作范围(range)内的元素。这些算法可以用于数组、容器如vector和list,以及其他满足相应迭代器要求的数据结构。以下是一些常用的C++ <algorithm> 中的算法及其使用示例。

1. std::sort:排序

对给定范围内的元素进行排序。默认情况下,按照升序排列,但也可以指定自定义比较函数。

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {5, 3, 1, 4, 2};
    std::sort(v.begin(), v.end());
    for (int i : v) std::cout << i << ' '; // 输出:1 2 3 4 5
    return 0;
}

2. std::count_if:计数满足条件的元素

计算范围内满足特定条件的元素数量。

#include <algorithm>
#include <vector>
#include <iostream>

bool is_even(int n) { return n % 2 == 0; }

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6};
    int count = std::count_if(v.begin(), v.end(), is_even);
    std::cout << "Even numbers: " << count << std::endl; // 输出:Even numbers: 3
    return 0;
}

3. std::find_if:查找第一个满足条件的元素

返回指向范围内第一个满足特定条件的元素的迭代器。

#include <algorithm>
#include <vector>
#include <iostream>

bool is_target(int n) { return n == 42; }

int main() {
    std::vector<int> v = {10, 20, 30, 42, 50};
    auto it = std::find_if(v.begin(), v.end(), is_target);
    if (it != v.end()) std::cout << "Found: " << *it << std::endl; // 输出:Found: 42
    else std::cout << "Not found" << std::endl;
    return 0;
}

4. std::transform:转换范围

对范围内的每个元素应用一个函数,并将结果存储在另一个容器或序列中。

#include <algorithm>
#include <vector>
#include <iostream>

int square(int n) { return n * n; }

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2(v1.size());
    std::transform(v1.begin(), v1.end(), v2.begin(), square);
    for (int i : v2) std::cout << i << ' '; // 输出:1 4 9 16 25
    return 0;
}

5. std::accumulate:累积值

对范围内的元素执行累积操作,如求和、求乘积等。

#include <algorithm>
#include <vector>
#include <iostream>
#include <numeric>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    int sum = std::accumulate(v.begin(), v.end(), 0);
    std::cout << "Sum: " << sum << std::endl; // 输出:Sum: 15
    return 0;
}

6. std::remove_if:移除满足条件的元素

将不满足特定条件的元素移动到范围的前端,并返回新的逻辑结束位置的迭代器。实际删除操作需配合容器的erase方法。

#include <algorithm>
#include <vector>
#include <iostream>

bool is_odd(int n) { return n % 2 != 0; }

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6};
    auto new_end = std::remove_if(v.begin(), v.end(), is_odd);
    v.erase(new_end, v.end()); // 实际删除操作
    for (int i : v) std::cout << i << ' '; // 输出:2 4 6
    return 0;
}
举报

相关推荐

0 条评论