【问题标题】:C++ sorting vector of struct explanationC++排序向量之struct解释
【发布时间】:2018-02-09 06:30:35
【问题描述】:

我正在开发一个学生信息系统,所以我有这个结构来存储学生信息:

struct student_info
{
   string name;
   int id;
   string course;
   int percent;
};

我也做了这个排序功能:

bool sorting(const container &a, const container &b) {
    return a.percent < b.percent;
}

这里,我从一个文件中读取并存储在结构中,将其推入结构的向量中,然后对其进行排序:

student_info raw_data;
vector <student_info> container;

ifstream infile("data.txt");

while(!infile.eof())
{
   infile >> raw_data.name >> raw_data.id >> raw_data.course >> raw_data.percent;  
   container.push_back(raw_data);
}   

sort(container.begin(), container.end(), sorting);

然后,我在某处看到了这个,但它没有清楚地解释为什么我不需要括号,即使排序是一个函数,比如为什么在调用 sort 时它只是 sorting 而不是 sorting()

【问题讨论】:

标签: c++ sorting vector struct


【解决方案1】:

函数的名称是sorting。表达式sorting(a, b) 将调用sorting 并返回一个布尔值。排序例程std::sort 将多次调用sorting

这个名字不好。我建议percent_less_than 而不是“排序”。此外,参数化是错误的。它比较学生的percent

bool percent_less_than(const student_info &a, const student_info &b) {
    return a.percent < b.percent;
}

【讨论】:

    【解决方案2】:

    Jive Dadson 正确回答了您的问题。 您还可以使用 lambda 语法进行排序。

    sort(container.begin(), container.end(), [=](const student_info &a, const student_info &b) {
        return a.percent < b.percent;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 2015-09-06
      相关资源
      最近更新 更多