Click here to Skip to main content
14,734,150 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi, this code won't compile correctly using std::sort and a struct.

How do I solve this?

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

struct StudentDataTypes
    std::string name{};
    int grade{};

int main()
    //Ask for Class_Size
    int Class_Size{};
    std::cout << "How big is the class?" << '\n';
    std::cin >> Class_Size;

    //Syntax format
    //std::vector<T> array(size);
    //Intialize a vector for the students called Vector_Student
    //T links to the struct StudentDataTypes
    //size is the Class_Size.
    std::vector<StudentDataTypes> Vector_Student(Class_Size);
    //Print Class Size
    std::cout << "There are " << Class_Size << " students." << '\n';

    //Get the Userinputs for the Class
    for (int i = 0; i < Class_Size; ++i)
        std::cout << "Please input the name of Student #" << i + 1 << '\n';
        std::cin >> Vector_Student[i].name;
        std::cout << "Please input the grade of Student #" << i + 1 << '\n';
        std::cin >> Vector_Student[i].grade;
    std::sort(Vector_Student.begin(), Vector_Student.end());

    //Print the required output
    for (int j = 0; j < Class_Size; ++j)
            << Vector_Student[j].name 
            << " got a grade of " 
            << Vector_Student[j].grade << '\n';
    return 0;

What I have tried:

1. Stack Overflow
"Closed. This question needs debugging details. It is not currently accepting answers.

Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.

Closed 11 hours ago.

(Private feedback for you)"
Updated 20-Nov-20 6:37am
KarstenK 20-Nov-20 13:40pm
The compiler is already talking to you: "Where is that comparator?". It like your "better half" demanding to clean up the kitchen ;-)

You need to tell sort how to compare the two structs. since there's no default comparison for non basic types. Do you want to sort by name or by grade, or by grade then by name, or ...?

Probably the easiest way is to add an operator< method to the struct:
struct StudentDataTypes
    std::string name{};
    int grade{};
    // order by name:
    bool operator<(const struct StudentDataTypes& other) const 
        return name <;

see further details here: std::sort -[^]
The sort function does not know how to sort a StudentDataTypes structure. You must provide a comparator, see <algorithm> functions | Microsoft Docs[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900