Как отсортировать массивы в структуре по значению - PullRequest
0 голосов
/ 02 мая 2020

Я хочу отсортировать студентов по их оценкам и распечатать студентов, чьи оценки являются самыми высокими и самыми низкими. Как я могу отсортировать массивы в структуре по их значениям?

#include <iostream>

using namespace std;

struct students {
    string name[20];
    int number;
    double score;
};

int main()
{
    struct students stu[20];
    int i;

    for(i = 0; i<20; i++) {
        cout<<"Please enter the name of the student.: ";
        cin>>stu[i].name;
        cout<<"Please enter the student number.: ";
        cin>>stu[i].number;
        cout<<"Please enter the score.: ";
        cin>>stu[i].score;
    }

}

Ответы [ 2 ]

2 голосов
/ 02 мая 2020

Есть много способов выполнить sh эту задачу, используя std :: sort.

  1. добавив оператор <() для структурирования ученика </li>
struct student {
    string name;
    int number;
    double score = 0;
    bool operator < (const student& other) const {
        return this->score < other.score;
    }
};
// Then just simply use std::sort
std::sort(std::begin(stu), std::end(stu));
Если вы не можете изменить структуру студентов, вы можете определить функцию сравнения
// define a function that compare students by score:
bool compareScore (const student& a, const student& b) {
    return a.score < b.score;
}

// then use std::sort with the compare function 
std::sort(std::begin(stu), std::end(stu), compareScore);
Вы также можете использовать функтор для выполнения работы
struct studentFunctor {
    bool operator()(const student& a, const student& b) {
        return a.score < b.score;
    }
};

// then use std::sort with the functor 
std::sort(std::begin(stu), std::end(stu), studentFunctor());
Использование C ++ 11 лямбда, который является предпочтительным способом сортировки
std::sort(std::begin(stu), std::end(stu),
          [](const student& a, const student& b){return a.score < b.score;})
1 голос
/ 02 мая 2020

Предполагая, что student::number должен быть уникальным, вы можете отсортировать его тремя различными способами.

#include <algorithm> // std::sort
#include <iostream>
#include <iterator>  // std::begin, std::end
#include <tuple>     // std::tie

// using namespace std; // bad habit

struct student {      // renamed since it contains info about one student only
    std::string name; // not an array of strings
    int number;
    double score;
};

int main()
{
    using std::cin, std::cout;
    student stu[20]; // struct not needed. student is typedef automatically in C++
    int i;

    for(i = 0; i<20; i++) {
        cout<<"Please enter the name of the student.: ";
        cin>>stu[i].name;
        cout<<"Please enter the student number.: ";
        cin>>stu[i].number;
        cout<<"Please enter the score.: ";
        cin>>stu[i].score;
    }

    // three comparison lambdas
    auto cmp_score = [](const student&a , const student& b) {
        return std::tie(a.score, a.number) < std::tie(b.score, b.number);
    };
    auto cmp_number = [](const student&a , const student& b) {
        return a.number < b.number;
    };
    auto cmp_name = [](const student&a , const student& b) {
        return std::tie(a.name, a.number) < std::tie(b.name, b.number);
    };

    // three ways to sort:
    std::sort(std::begin(stu), std::end(stu), cmp_score);
    std::sort(std::begin(stu), std::end(stu), cmp_number);
    std::sort(std::begin(stu), std::end(stu), cmp_name);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...