C ++通过类中的变量对向量进行双重排序 [英] C++ double sorting vector by variables in a class
问题描述
我有一个用户类型对象的向量,并想按第一个字符串变量然后按第二个字符串变量对向量进行排序.
I have a vector of a user type object and want to sort the vector by the first string variable and then by the second string variable.
class MyClass{
private:
string a;
string b;
int x;
double y;
}
我在主代码中有一个向量,该向量已将数据解析为取决于文件的任意数量的元素.
I have a vector in the main code that has the data already parsed into any number of elements depending on the file.
int main(){
vector<MyClass> data;
// Code that fills the data variable. This all works and can be displayed via print function
/*CODE TO SORT BY THE FIRST STRING THEN SORT AGAIN BY THE SECOND STRING
*
* -- Sort code here --
*
*/
return 0;
}
我的问题是2折:
1)您如何基于向量内部的变量来进行向量处理?应该根据类中的第一个字符串(标记为a的字符串)对向量进行排序.
1) How do you do a sort of the vector based on a variable inside that vector? The vector should be sorted based on the first string in the class (the string labeled a).
2).您将如何进一步对向量进行排序,以便在对第一个字符串进行排序之后,对第二个字符串进行排序,以便输出看起来像这样(出于所有目的和目的,第二个字符串(字符串b)中的数字不是整数,而是字符串) :
2). How would you further sort the vector so that once the first string is sorted, sort the second string so that the output may look something like this (for all intents and purposes the numbers in the second string (string b) are strings not integers):
string a: a string b: 1
string a: a string b: 2
string a: a string b: 3
string a: a string b: 4
string a: b string b: 1
string a: b string b: 2
string a: b string b: 3
string a: b string b: 4
推荐答案
将a
和b
公开,然后尝试执行以下操作:
Make a
and b
public and try something like this:
std::sort(data.begin(), data.end(), [](const MyClass& v1, const MyClass& v2) {
return (v1.a == v2.a) ? (v1.b < v2.b) : (v1.a < v2.a);
});
您可以保留它们的私密性,也可以使用getter来获取其价值.正如ZDF所述,您也可以创建<
运算符.在Myclass
中添加以下内容:
You can keep them private and use getter for getting their value too. As ZDF mentioned, you can create <
operator too. add following to Myclass
:
MyClass {
...
public:
bool operator<(const MyClass& v2) const {
return (a == v2.a) ? (b < v2.b) : (a < v2.a);
}
}
然后像这样的sort
:
std::sort(data.begin(), data.end());
这篇关于C ++通过类中的变量对向量进行双重排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!