MST

星途 面试题库

面试题:C++中如何在STL算法sort中启用并行排序

在C++ STL的sort算法中,如何利用并行算法来实现并行排序?请描述实现的关键步骤,并给出一个简单示例代码。
14.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

关键步骤

  1. 引入并行算法头文件:在C++ 中,使用并行算法需要引入 <execution> 头文件。
  2. 选择执行策略<execution> 头文件提供了几种执行策略,例如 std::execution::seq(顺序执行)、std::execution::par(并行执行)和 std::execution::par_unseq(并行且可能无序执行)。我们需要选择 std::execution::parstd::execution::par_unseq 来实现并行排序。
  3. 调用 std::sort 并传入执行策略:将选择的执行策略作为第一个参数传递给 std::sort 函数,替代原来的默认顺序执行方式。

示例代码

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

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

    // 使用并行执行策略进行排序
    std::sort(std::execution::par, nums.begin(), nums.end());

    // 输出排序后的结果
    for (int num : nums) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上述代码中:

  1. 首先引入了 <iostream> 用于输出,<algorithm> 提供 std::sort 函数,<vector> 定义向量容器,<execution> 提供并行执行策略。
  2. 创建一个 std::vector<int> 并初始化一些数据。
  3. 使用 std::sort 并传入 std::execution::par 执行策略来对向量进行并行排序。
  4. 最后遍历输出排序后的向量元素。