我之前发过帖子,得到了一些非常有帮助的回复。我需要将文本文件中的人的信息(例如 ID、年龄等)读入不同的数组中。 记录是这样的 2012317109 Jamie Carles Smith 男 65(不同位的信息用 TAB 分隔,行以换行符结尾)
但是,关于 ID 号,我被告知使用提取运算符 (<<) 将 ID 号作为整数而不是字符串。
然后我必须按字母字符串顺序对这些记录进行排序,然后将它们放入输出文件中。
到目前为止,我有以下内容。我该如何进行?我不会使用 map 或 vector ,我需要使用数组。
#include <iostream>
#include <fstream>
using namespace std;
void selection_sort( double x[], int length)
{
int i, j, k;
double t;
for (i=0; i<length-1; ++i) {
k = i; //find next smallest elm, x[k]
for (j=i+1; j< length; ++j)
if (x[k] > x[j]) k = j;
//swap x[i] with x[k]
t = x[i]; x[i] = x[k]; x[k] = t;
}
}
int main () {
ifstream fin;
ofstream fout;
fin.open("input.txt");
fout.open("output.txt");
if (fin.fail()) {
cout << "Fail to open inout.txt" << endl;
exit(1);
}
struct row{string ID, name, rest;};
int x;
fout << x << endl;
row *rows=new row[x];
for (int i=0; i<x; ++i) {
getline (fin, rows[i].ID, '\t'); // ID
getline (fin, rows[i].name, '\t'); // name
getline (fin, rows[i].rest );
}
selection_sort (row[], x);
//complier error this line: expected primary expression before [ token.
}
最佳答案
最简单的方法可能是使用 std::sort
(来自标题 <algorithm>
),并定义一个
bool operator<(row const& lhs, row const& rhs)
{
// delegates to operator< for std::string
return lhs.name < rhs.name;
}
然后调用STL算法
// uses the above defined operator< for row objects
std::sort(rows, rows + x);
然后写入排序后的输出。
关于c++ - 按字母顺序排列的字符串数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987183/