【发布时间】:2014-09-10 04:48:21
【问题描述】:
我的问题在于最后一个函数 print_valid_data。我应该从数组A[] 中删除第二个最小值。删除值后,数组中的元素需要移动,数组中的最后一个空位为空。我在函数中所做的是跳过它,并打印出剩下的内容。我将如何通过删除然后转移来做到这一点?
旁注:Var.h 是一个文件,只有数据“const int NUM = 10”可能会发生变化,它用于数组的索引。 “data.txt”文件有一些整数(程序占>10个数字或Load_file_to_array函数读入的。
#include <iostream>
#include "Var.h"
#include <fstream>
#include <string>
using namespace std;
void Load_File_To_Array(int A[], string filename, int size);
int Get_2nd_Smallest(int A[], int size);
void Print_valid_data(int A[], int SecondMin, int size);
int main()
{
int A[NUM];
int size = NUM;
int SecondMin = 0;
string filename = "Data.txt";
Load_File_To_Array(A, filename, size);
Get_2nd_Smallest(A, size);
Print_valid_data(A, SecondMin, size);
cout << endl;
system("Pause");
return 0;
}
void Load_File_To_Array(int A[], string filename, int size)
{
ifstream infile;
infile.open(filename);
cout << "The array is: ";
for (int i = 0; i < NUM; i++)
{
if (infile.eof())
break;
infile >> A[i];
cout << A[i] << ", ";
}
return;
}
int Get_2nd_Smallest(int A[], int size)
{
int Min = A[0];
int SecondMin = 0;
for (int i = 0; i < NUM; i++)
{
if (Min > A[i])
Min = A[i];
}
//Exchange-sort to sort the array in descending order
int j, k;
int counter;
for (j = 0; j < (size - 1); j++)
{
for (k = (j + 1); k < size; k++)
{
if (A[j] < A[k])
{
counter = A[j];
A[j] = A[k];
A[k] = counter;
}
}
}
for (int n = (NUM - 1); n > -1; n--)
{
SecondMin = A[n];
if (SecondMin >= 0)
{
SecondMin = A[n - 1];
break;
}
else;
}
cout << endl << "The minimum number is: " << Min << endl;
cout << "The second smallest integer is: " << SecondMin << endl;
return SecondMin;
}
void Print_valid_data(int A[], int SecondMin, int size)
{
cout << "The new array is: ";
for (int i = 0; i < size; i++)
{
if (A[i] != SecondMin)
{
cout << A[i] << ", ";
}
}
return;
}
【问题讨论】:
-
一个快速而肮脏的方法是获取第二小的数字的索引,然后再次遍历数组,为该位置(从空点开始)分配下一个点的值。当你到达数组的末尾时,只需分配最后一个位置,null。
-
尝试使用具有擦除方法的矢量容器。
-
@Tracer 我知道你可以使用向量,但这不是我应该编写这个程序的方式。
-
如果您反向排序(从头到尾),删除第二小的应该只需要交换排序算法的两次迭代。除了忽略它之外,它还需要您对
Get_2nd_Smallest的结果做一些事情,因为现在您只是将0传递给Print_valid_data函数。之后,只需交换最后两个元素并将大小减小一即可。生成的 0..orig_size-2 序列将不包含最小元素,并以最小元素结束。
标签: c++ arrays visual-studio sorting