奇怪的std :: sort行为

Dim*_*htz 0 c++ sorting

我试图使用std::stringID(结构的成员)对结构数组进行排序.这是代码:

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;
});
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都按预期工作.例如,以下数据:

liu 90 80 90 100 85
ols 95 95 90 93 85
kum 90 85 85 95 92

将分类到:

ols 95 95 90 93 85
liu 90 80 90 100 85
kum 90 85 85 95 92

但是,如果我只是改变:

return r1.ID > r2.ID;
Run Code Online (Sandbox Code Playgroud)

至:

return r1.ID < r2.ID;
Run Code Online (Sandbox Code Playgroud)

对于同一个例子,我会得到:

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

怎么可能呢?

Fra*_*eux 6

std::array<Row, 50> records{};是一个包含50个实例的数组Row.如果您的数组包含50个元素,并且您只指定其中的3个元素,则数组中将保留47个默认构造元素.当您从文件中读取并且其余的默认构造元素在数组的前面进行排序时,您似乎没有为数组中的所有元素赋值.

std::vector如果在编译时您不确定需要多少元素,请考虑使用.