【发布时间】:2016-08-09 14:00:37
【问题描述】:
这是一个工作程序,我一直在尝试从文件字符串和双精度的输入中学习 C++,并将它们放入它们的透视数组中。我坚持的是在对字符串进行排序时,我想按升序对双精度数组进行排序,并将分数与它们关联的名称保持一致。在我继续学习如何操作它们之前,我试图在不使用向量的情况下学习它,这就是在有人问之前不使用向量的原因。 最好对 2d 数组的列进行排序,而不是用 1d 数组对它们进行排序,还是只使用一个语句来完成这一切?还有什么是这个应用程序的最佳排序算法? 到目前为止,我的尝试都失败了,所以我向这里的社区寻求帮助。逻辑很可能是一些我还没有掌握的简单概念。我们都必须从某个地方开始。预先感谢您的帮助。
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void ArraySort (string x[], double y[][3], int length);
int main()
{
ifstream inFile;
inFile.open("bowlers2.txt");
const int SIZE = 10;
int i,j;
double scores[10][3];
string names[SIZE];
string mystring;
if (!inFile)
{
cout << "Can not open the input file"
<< " This program will end."<< "\n";
return 1;
}
for(i = 0; i < SIZE; i++)
{
getline(inFile, names[i]);
for(j = 0; j < 3; j++)
{
getline(inFile, mystring);
scores[i][j] = atoi(mystring.c_str());
}
}
for(int i=0;i<SIZE;i++)
{
cout << names[i] << "\n";
for(j = 0; j < 3; j++)
cout << scores[i][j] << "\n";
}
inFile.close();
ArraySort (names, scores, SIZE);
return 0;
}
void ArraySort (string x[], double y[][3], int LENGTH)
{
int i,j;
string sValue;
double dValue;
for(i = 1; i < LENGTH; i++)
{
sValue = x[i];
for(j = i - 1; j >= 0 && x[j] > sValue; j--)
{
x[j + 1] = x[j];
}
x[j + 1] = sValue;
}
cout << "\n";
for(int i=0;i<LENGTH;i++)
{
cout << x[i] << "\n";
for(j = 0; j < 3; j++)
cout << y[i][j] << "\n";
}
}
程序读取的文件:
Linus too good
100
23
210
Charlie brown
1
2
12
Snoopy
300
300
100
Peperment Patty
223
300
221
Pig Pen
234
123
212
Red Headed Girl
123
222
111
Marcey
1
2
3
keith hallmark
222
300
180
anna hallmark
222
111
211
roxie hallmark
100
100
2
【问题讨论】:
-
我建议您在两个独立的操作中重新排列数字集合并在集合中对数字进行排序。尝试一下,并告诉我们您需要帮助的操作。
标签: c++ sorting multidimensional-array