在c++中打印未排序列表中的最大整数
Printing J Largest integers from unsorted list in C++
我正试图编写一个函数,从未排序的值数组中打印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,但不要忘记删除它。
相关文章:
- 跟随整数索引列表的自定义类迭代器
- 如何在 sqlite3 中的表中添加整数列表
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 带有整数的变量参数列表
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- 使用整数初始化列表初始化长双精度的向量
- 最大数量.给定一个非负整数列表,排列它们以使它们形成最大的数字
- C++:随机数列表:x 个随机整数
- 有效比较整数列表与C++中给定的整数
- 如何在逗号分开列表中解析字段并将其转换为整数
- 输入正整数或负整数列表,以使用开关函数 c++ 确定数字是偶数还是奇数
- 使用包含每个重复数量的列表生成重复,上升整数的顺序,并用推力
- 如何使用整数列表在LLVM中初始化整数数组
- 如何扩展类模板整数列表
- 如何生成升序随机整数列表
- 从文本文件将整数读入简单的链表中.然后对整数列表进行气泡排序并读出到另一个文件
- 填充整数列表比填充整数向量快 100 倍
- C 98中整数集列表的初始化
- 在 C++ 提升 Python 列表中附加整数的错误