[英]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;
}
I have an issue with a Vector Struct tutorial.我有一个矢量结构教程的问题。
I'm using Visual Studio 2019 and there's a peculiar scenario where the compiler doesn't give me any warning at all.我正在使用 Visual Studio 2019 并且有一个特殊的场景,编译器根本没有给我任何警告。 If I debug it, the first warning appears on line 1544, way out of bounds.如果我调试它,第 1544 行会出现第一个警告,超出范围。 The above code will actually sort of compile, run and crash.上面的代码实际上会编译、运行和崩溃。
I know the issue lies in the sorting but I can't figure it out.我知道问题在于排序,但我无法弄清楚。
std::sort
requires you to implement operator<
for your datatype. std::sort
要求您为您的数据类型实现operator<
。 Here in this case adding following definition in your class will get your code to compile在这种情况下,在您的类中添加以下定义将使您的代码编译
bool operator<(const StudentDataTypes& that) {
return this->grade < that.grade;
}
Update: Alternatively as sugested by Casey, we can use custom sort comparator.更新:或者如 Casey 所建议的那样,我们可以使用自定义排序比较器。 Here is the sample code for the same.这是相同的示例代码。
std::sort(Vector_Student.begin(), Vector_Student.end(), [](const StudentDataTypes& a, const StudentDataTypes&b) { return a.grade < b.grade; });
Here is the answer.这是答案。 I'm posting it in the answers for how to sort a vector-struct.我将它发布在如何对向量结构进行排序的答案中。
Step 1:第1步:
bool compareTwoStudents(StudentDataTypes a, StudentDataTypes b) {
if (a.grade != b.grade)
return a.grade > b.grade;
return a.grade==b.grade;
}
Step 2:第2步:
std::sort(Vector_Student.begin(), Vector_Student.end(),compareTwoStudents);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.