我试图使用std::string ID (结构的成员)对结构数组进行排序。下面是代码:
struct Row {
std::string ID;
std::array<float, 5> scores;
float avgScore;
};
std::array<Row, 50> records{};
// ...
// Open a file, read some data and store them into records
// ...
// Sort the data
std::sort(records.begin(), records.end(), [](const Row& r1, const Row& r2) {
return r1.ID > r2.ID;
});到目前为止,一切都如期而至。例如,以下数据:
刘氏90 80 90 100 85 ols 95 95 90 93 85 金90 85 85 95 92
将被排序为:
ols 95 95 90 93 85 刘氏90 80 90 100 85 金90 85 85 95 92
但是,如果我简单地更改:
return r1.ID > r2.ID;至:
return r1.ID < r2.ID;对于同样的例子,我将得到:
0 0 0 0 0 0 0 0 0
怎么可能呢?
发布于 2017-10-27 17:33:40
std::array<Row, 50> records{};是一个包含确切50个Row实例的数组。如果数组包含50个元素,并且只指定其中3个元素,则数组中保留了47个默认构造元素。当您从文件中读取时,似乎没有为数组中的所有元素赋值,而其余的默认构造元素正在数组的前面排序。
如果在编译时不确定需要多少元素,请考虑使用std::vector。
https://stackoverflow.com/questions/46980397
复制相似问题