我的问题是最后一个函数print_valid_data。我应该删除数组A[]
中的第二个最小值。删除该值后,数组中的元素需要移位,数组中的最后一个打开位置为空。我在我的功能中所做的是跳过它,并打印出剩下的内容。如何删除然后转移呢?
附注:Var.h是一个只有数据的文件" const int NUM = 10"可能会有变化,它是数组的索引。 " data.txt"文件有一些整数(程序占> 10个数字或< 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;
}
答案 0 :(得分:1)
以下可能有所帮助,删除是通过复制前一个值来完成的:
const int size = 6;
int v[] = {5, 6, 8, 2, 3, 1};
std::partial_sort(std::begin(v), std::begin(v) + 2, std::end(v));
std::cout << "The minimum number is: " << v[0] << std::endl;
std::cout << "The second smallest integer is: " << v[1] << std::endl;
std::copy(std::begin(v) + 2, std::end(v), std::begin(v) + 1);
std::cout << "remaining values: ";
for (int i = 0; i != size - 1; ++i) {
std::cout << v[i] << ", ";
}