C++ 按字符串C+对矢量中存储的对象进行排序+;

C++ 按字符串C+对矢量中存储的对象进行排序+;,c++,sorting,vector,C++,Sorting,Vector,想象一个具有字符串值的类 class Test { public: string name; }; 它存储在向量中 vector<Test> d; 您可以创建一个比较器 bool comp(const Test &test1, const Test &test2){ return test1.getName() < test2.getName(); } bool comp(常量测试和测试1、常量测试和测试2){ 返回test1.getNa

想象一个具有字符串值的类

class Test {
public:
    string name;
};
它存储在向量中

vector<Test> d;

您可以创建一个比较器

bool comp(const Test &test1, const Test &test2){
    return test1.getName() <  test2.getName();
}
bool comp(常量测试和测试1、常量测试和测试2){
返回test1.getName()

或者您可以重载
运算符
comp
将是一个函数,返回
bool
以指示两个参数的比较。在您的情况下,它应该如下所示:

bool compare ( const Test& s1, const Test& s2 )
{
    return ( s1.name < s2.name );
}
bool比较(常数测试&s1,常数测试&s2)
{
返回(s1.name

您的调用将是:
sort(d.begin(),d.end(),compare)

通常对这类事情非常有用。@Paranix,是的,任何可调用的对象。我认为最好使用
const Test&s1
而不是简单地
Test s1
作为参数,以避免复制对象。
bool operator < (const Test &test){
    return name < test.name;
}
bool compare ( const Test& s1, const Test& s2 )
{
    return ( s1.name < s2.name );
}