1

抱歉,如果问题标题术语有误,但这是我想要做的。我需要对对象向量进行排序,但与典型的比较“小于”方法相反,我需要根据一些字符串重新定位对象ID 属性,以便每个相同类型的成员按连续顺序定位,如下所示:

[id_town,id_country,id_planet,id_planet,id_town,id_country]

变成这样:

[id_town,id_town,id_country,id_country,id_planet,id_planet]

id_ 属性是字符串。

4

1 回答 1

9

std::sort具有第三个参数,可用于传递用作自定义比较器的布尔谓词。根据您的规范编写您自己的比较器并使用它。

例如:

struct foo
{
    std::string id;

    foo(const std::string& _id) : id( _id ) {}
};

//Functor to compare foo instances:
struct foo_comparator
{
    operator bool(const foo& lhs , const foo& rhs) const
    {
        return lhs.id < rhs.id;
    }
};

int main()
{
    std::vector<foo> v;

    std::sort( std::begin(v) , std::end(v) , foo_comparator );
}

此外,在 C++11 中,您可以使用 lambda:

std::sort( std::begin(v) , std::end(v) , [](const foo& lhs , const foo& rhs) { return lhs.id < rhs.id; } );

最后,您还可以重载比较运算符(operator>operator<)并使用标准库提供的比较器,例如std::greater

struct foo
{
    std::string id;

    foo(const std::string& _id) : id( _id ) {}

    friend bool operator<(const foo& lhs , const foo& rhs)
    {
        return lhs.id < rhs.id;
    }

    friend bool operator>(const foo& lhs , const foo& rhs)
    {
        return rhs < lhs;
    }

    friend bool operator>=(const foo& lhs , const foo& rhs)
    {
        return !(lhs < rhs);
    }

    friend bool operator<=(const foo& lhs , const foo& rhs)
    {
        return !(lhs > rhs);
    }
};


int main()
{
    std::vector<foo> v;

    std::sort( std::begin(v) , std::end(v) , std::greater );
}
于 2013-09-06T14:21:12.183 回答