在STL容器中排序

时间:2013-09-06 14:13:04

标签: c++ algorithm

很抱歉,如果问题标题术语有误,但这就是我想要做的事情。我需要对对象的矢量进行排序,但与typical comparison"小于"相反。方法我需要根据一些字符串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_ property是string。

1 个答案:

答案 0 :(得分: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 );
}