面试题答案
一键面试关键步骤
- 引入并行算法头文件:在C++ 中,使用并行算法需要引入
<execution>
头文件。 - 选择执行策略:
<execution>
头文件提供了几种执行策略,例如std::execution::seq
(顺序执行)、std::execution::par
(并行执行)和std::execution::par_unseq
(并行且可能无序执行)。我们需要选择std::execution::par
或std::execution::par_unseq
来实现并行排序。 - 调用
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;
}
在上述代码中:
- 首先引入了
<iostream>
用于输出,<algorithm>
提供std::sort
函数,<vector>
定义向量容器,<execution>
提供并行执行策略。 - 创建一个
std::vector<int>
并初始化一些数据。 - 使用
std::sort
并传入std::execution::par
执行策略来对向量进行并行排序。 - 最后遍历输出排序后的向量元素。