想象一下具有字符串值的类。
class Test {
public:
string name;
};
是存储在 vector 中
vector<Test> d;
我想使用 sort() 函数按名称值的字母顺序对 vector 中的对象进行排序。我知道 sort() 函数有第三个参数某种排序函数,但我不知道如何编写此函数。
sort(d.begin(),d.end(),comp());
comp () { ? }
最佳答案
你可以创建一个比较器
bool comp(const Test &test1, const Test &test2){
return test1.getName() < test2.getName();
}
或者你可以重载 operator <
在你的类里面
bool operator < (const Test &test){
return name < test.name;
}
请注意,如果您重载 operator <
,那么就不需要在排序函数中添加第三个参数了。
关于c++ - 按字符串C++对存储在 vector 中的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287246/