繁体   English   中英

std::vector 结构学生示例

[英]std::vector Struct Student example

#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;
    }
    
    //Sort
    std::sort(Vector_Student.begin(), Vector_Student.end());

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

我有一个矢量结构教程的问题。

我正在使用 Visual Studio 2019 并且有一个特殊的场景,编译器根本没有给我任何警告。 如果我调试它,第 1544 行会出现第一个警告,超出范围。 上面的代码实际上会编译、运行和崩溃。

我知道问题在于排序,但我无法弄清楚。

std::sort要求您为您的数据类型实现operator< 在这种情况下,在您的类中添加以下定义将使您的代码编译

bool operator<(const StudentDataTypes& that) {
    return this->grade < that.grade;
}

更新:或者如 Casey 所建议的那样,我们可以使用自定义排序比较器。 这是相同的示例代码。

std::sort(Vector_Student.begin(), Vector_Student.end(), [](const StudentDataTypes& a, const StudentDataTypes&b) { return a.grade < b.grade; });

这是答案。 我将它发布在如何对向量结构进行排序的答案中。

第1步:

bool compareTwoStudents(StudentDataTypes a, StudentDataTypes b) {
    if (a.grade != b.grade)
        return a.grade > b.grade;
    return a.grade==b.grade;
} 

第2步:

std::sort(Vector_Student.begin(), Vector_Student.end(),compareTwoStudents); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM