简体   繁体   English

奇怪的std :: sort行为

[英]Weird std::sort behavior

I am trying to sort an array of structs using an std::string ID (member of the struct). 我正在尝试使用std::string ID(结构成员)对结构数组进行排序。 Here's the code: 这是代码:

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;
});

So far everything works as expected. 到目前为止,一切正常。 For example, following data: 例如,以下数据:

liu 90 80 90 100 85 刘90 80 90 100 85
ols 95 95 90 93 85 醇95 95 90 93 85
kum 90 85 85 95 92 姜90 85 85 95 92

will be sorted to: 将被分类为:

ols 95 95 90 93 85 醇95 95 90 93 85
liu 90 80 90 100 85 刘90 80 90 100 85
kum 90 85 85 95 92 姜90 85 85 95 92

However, if I simply change: 但是,如果我只是更改:

return r1.ID > r2.ID;

to: 至:

return r1.ID < r2.ID;

for the same example, I will get: 对于同一示例,我将得到:

0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0

How's that even possible? 那怎么可能呢?

std::array<Row, 50> records{}; is an array containing exactly 50 instances of Row . 是一个数组,其中恰好包含Row 50个实例。 If your array contains 50 elements and you only specify 3 of them, there are 47 default constructed elements left in your array. 如果您的数组包含50个元素,而您仅指定了3个元素,则数组中还有47个默认的构造元素。 It seems that you do not assign a value to all of the elements in your array when you read from your file and the remaining default constructed elements are being sorted at the front of the array. 当您从文件中读取数据时,似乎没有为数组中的所有元素分配值,而其余的默认构造元素正在数组的前面进行排序。

Consider using std::vector instead if, at compile time, you aren't certain how many elements you will need. 如果在编译时不确定是否需要多少个元素,可以考虑使用std::vector代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM