Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 排序算法值得在这里实现吗?_C++_Sorting - Fatal编程技术网

C++ 排序算法值得在这里实现吗?

C++ 排序算法值得在这里实现吗?,c++,sorting,C++,Sorting,我有一个正整数列表,我想在变量h1、h2和h3中存储3个最大的值。其余的值是无关的 我曾考虑过使用int*和realloc在内存被填满时对其进行排序,然后使用合适的排序算法来管理它们,但这真的值得吗?因为我实际上不需要对整个数组进行排序,所以我只是这样做: if (currentVal > h3) { h3 = currentVal; if (currentVal > h2) { h3 = h2; h2 = currentVal;

我有一个正整数列表,我想在变量
h1
h2
h3
中存储3个最大的值。其余的值是无关的

我曾考虑过使用
int*
realloc
在内存被填满时对其进行排序,然后使用合适的排序算法来管理它们,但这真的值得吗?因为我实际上不需要对整个数组进行排序,所以我只是这样做:

if (currentVal > h3) {
    h3 = currentVal;
    if (currentVal > h2) {
        h3 = h2;
        h2 = currentVal;
        if (currentVal > h1) {
            h2 = h1;
            h1 = currentVal;
        }
    }
}

这感觉像是一种愚蠢而静态的方式,但它是有效的。我是否应该实施一个排序算法,如果还没有,有什么建议可能合适吗?

对于“前三名”,这是完全合理的。对于具有较大(但固定)值的
k
“top k”,您可能希望尝试使用。

您可以通过以下方式在数组中找到任意数量的最大元素

#include <iostream>
#include <algorithm>
#include <functional>
#include <array>

template <size_t N> 
void n_max_element( const int a[],
                    size_t n,
                    std::array<int, N> &nmax )
{
    std::partial_sort_copy( a, a + n, 
                            nmax.begin(), nmax.end(), 
                            std::greater<int>() );
}   

int main() 
{
    const size_t N = 10;
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    std::random_shuffle( a, a + N );

    std::array<int, 3> max;

    n_max_element( a, N, max );

    std::cout << "max[0] = " << max[0] 
              << ", max[1] = " << max[1] 
              << ", max[2] = " << max[2] << std::endl;

    return 0;
}

为您使用
std::sort()
实际上有什么不对?无需排序。这样做没关系。(虽然如果列表足够短,排序确实比重新发明轮子更方便)因为只存储3个值,排序的开销可能比代码长。查看汇编语言列表。
max[0] = 9, max[1] = 8, max[2] = 7