【问题标题】:Sorting elements in struct in C++ [duplicate]在C ++中对结构中的元素进行排序[重复]
【发布时间】:2014-01-13 09:49:30
【问题描述】:
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct properties{
    int index;    // student's index number
    string name;  // name of student
    int points;   // points of exam

    bool sorter(properties a, properties b){
        return a.points < b.points;
    }

};

int main()
{
    properties students[6];

    vector<int> v;

    for(int i = 0; i < 6; i++){
        cin >> students[i].index >> students[i].name >> students[i].points;
    }

    for(int i = 0; i < 6; i++){
        v.push_back(students[i].points);
    }

    stable_sort(students.begin(), students.end(), sorter);

    return 0;
}

我有以下程序,现在我必须扩展它以按从最高点到最低点的排序顺序打印元素。我需要最小和最简单的代码,因为在我的情况下时间不是问题。任何帮助表示赞赏。

更新:我收到两个错误:

error: expected primary-expression before ',' token
error: expected primary-expression before '+' token

在这一行:

sort(properties, properties + 5);

【问题讨论】:

  • @DCoder 我不明白这个例子......对不起
  • 你试过std::sort吗?
  • @Erbureth 是的......但我不知道如何用 struct 来实现它......我以前用它来处理数组,它工作得很好,但我无法做到在这种情况下工作..
  • std::sort的第二种形式,它允许你指定你自己的比较函数。链接的文档包括示例实现。
  • 你没有阅读文档

标签: c++ sorting struct


【解决方案1】:

我只是给你一些连续的提示:

  1. 创建 std::vector 并将数据推送到:

    vector<properties> students;
    
  2. 编写比较两个结构并返回比较结果的函数。不要让它成为你结构的成员。请注意,我已将其重命名:

    bool less_than(properties const& first, properties const& second) 
    //my fault. Compiler is trying to call std::less<>() function instead of your.
    {  
      return first.points < second.points;    
    }  
    
  3. 调用 std::sort 函数:

    sort(students.begin(), students.end(), less_than); 
    
  4. students 结构中的数据将按降序排列。

此代码有效:http://ideone.com/iMWcfi

【讨论】:

  • 谢谢,我马上试试。还有一个问题。学生的其他属性是否会以相同的顺序排列?就像排序时最先出现的学生的名字保持不变?
  • @user2943407 见std::stable_sort
  • @Erbureth 所以它与 sort() 相同,只是名称不同,但是我有一个问题。当我在 main() 中使用 stable_sort() 时,它表示未声明 less 并且在“学生”中对成员“开始”和“结束”的请求是非类类型“属性 [6]”。当我在结构中声明排序时,它说学生没有被声明。我做错了什么??
  • @user2943407 不断更新问题中的代码,以便我们看到您在尝试什么。
  • @user2943407 将sorter 声明为static (static bool sorter(...){...}) 并将其称为sort(students, students + 6, properties::sorter);
【解决方案2】:

参见例如https://stackoverflow.com/a/10308722/1467943

bool operator <(const properties &a, const properties &b) {
  return a.points < b.points;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多