在c++中打印未排序列表中的最大整数

Printing J Largest integers from unsorted list in C++

本文关键字:列表 整数 排序 c++ 打印      更新时间:2023-10-16

我正试图编写一个函数,从未排序的值数组中打印K个最大整数。我做错了什么?

#include <iostream>
void printKLargest(int array[], int k, int size);
int main() {
    int array[5] = {1, 100, 2, 500, 6};
    int k = 2;
    int size = sizeof(array)/sizeof(array[0]);
    findKLargest(array, k, size);
}
void printKLargest(int array[], int k, int size) {
    int *largest = new int[k];
    for (int i = 0; i < size; i++) {
        if (array[i] > largest[0]) {
            largest[0] = array[i];
            for (int j = 1; j < k && largest[j-1] > largest[j]; j++) {
                int t = largest[j]; largest[j] = largest[j-1]; largest[j-1] = t;
            }
        }
    }
    for (int i = 0; i < k; i++) {
        std::cout << largest[i] << "n";
    }
}

上面的代码只正确打印largest的第一个整数。在C中,我能够使用malloc让它正确工作,但在c++中使用new让我有点失望。谢谢你。

edit -如果我将行int *largest = new int[k]更改为int *largest = (int *)malloc(sizeof(k));,我将获得所需的值。有人能解释一下为什么会这样吗?

至少由large所指向的已分配元素没有初始化

int *largest = new int[k];

因此程序具有未定义的行为。

在赋值

之后
if (array[i] > largest[0]) {
   largest[0] = array[i];

您丢失了largest[0]的值,可以在largest[1]中复制。

如果使用标头<algorithm>

中声明的标准算法std::partial_sort_copy,可以简单地完成赋值。例如

#include <vector>
#include <algorithm>
#include <functional>
//...
void printKLargest( const int array[], size_t n, size_t k ) 
{
    if ( n < k ) k = n;
    std::vector<int> largest( k );
    std::partial_sort_copy( array, array + n, 
                            largest.begin(), largest.end(),
                            std::greater<int>() );
    for ( int x : largest ) std::cout << x << ' ';
    std::cout << std::endl;
}

下面是一个示范程序

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
void printKLargest( const int array[], size_t n, size_t k ) 
{
    if ( n < k ) k = n;
    std::vector<int> largest( k );
    std::partial_sort_copy( array, array + n, 
                            largest.begin(), largest.end(),
                            std::greater<int>() );
    for ( int x : largest ) std::cout << x << ' ';
    std::cout << std::endl;
}
int main()
{
    int a[] = { 5, 3, 7, 6, 3, 9, 0 };
    printKLargest( a, sizeof( a ) / sizeof( *a ), 2 );
}

程序输出为

9 7

可以使用动态分配的数组代替vector,但不要忘记删除它。