[英]Sort objects stored in vector by string C++
想象一下带有字符串值的类。
class Test {
public:
string name;
};
是存储在向量中
vector<Test> d;
我想使用sort()函数按照字母名称值对矢量字母中的对象进行排序。 我知道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 <
,则不需要在sort函数中添加第三个参数。
comp
将是一个函数,它将返回一个bool
来指示两个参数的比较。 在你的情况下,它应该看起来像:
bool compare ( const Test& s1, const Test& s2 )
{
return ( s1.name < s2.name );
}
你的调用将是: sort ( d.begin(), d.end(), compare );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.