c++ - 在数组中找到两个最小 int64 元素的最快方法

标签 c++ optimization minimum

我有大小从 1000 到 10000 (1k .. 10k) 的数组。每个元素都是 int64。我的任务是找到数组中的两个最小元素,即最小元素和剩余元素中的最小元素。

我想在 C++ 中为 Intel Core2 或 Corei7(cpu 模式为 64 位)获得最快的单线程代码。

这个函数(从数组中取最小的 2 个)是热点,它嵌套在两个或三个迭代次数巨大的 for 循环中。

当前代码如下:

int f()
{
    int best; // index of the minimum element
    int64 min_cost = 1LL << 61;
    int64 second_min_cost = 1LL << 62;
    for (int i = 1; i < width; i++) {
     int64 cost = get_ith_element_from_array(i); // it is inlined
     if (cost < min_cost) {
        best = i;
        second_min_cost = min_cost;
        min_cost = cost;
     } else if (cost < second_min_cost) {
        second_min_cost = cost;
     }
    }
    save_min_and_next(min_cost, best, second_min_cost);
}

最佳答案

partial_sortnth_element

std::vector<int64_t> arr(10000); // large

std::partial_sort(arr.begin(), arr.begin()+2, arr.end());
// arr[0] and arr[1] are minimum two values

如果你只想要第二低的值,nth_element 就是你的选择

关于c++ - 在数组中找到两个最小 int64 元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793419/

相关文章:

c++ - 在 eclipse 中链接 gsl 库时 undefined reference

c++ - 我可以通过 G++ 将 CUDA 与 C++ 程序一起使用吗?或者 CUDA 只能用 GCC 编译?

javascript - 有效地减少时间受限任务之间的等待时间

javascript - 最小值不起作用

c++ - 生成指向回调函数的常量指针数组

c++ - 如何在用户模式下从内核模式驱动程序向二进制文件发送和接收数据

html - PageSpeed 工具的奇怪修复

javascript - 隐藏数千个 <li> 元素的最快方法?

python - 具有 NA 的两列的条件最小值

c++ - 在for循环中找到最小值并保留它的索引