c++ - STL 容器中的有序排序

标签 c++ algorithm

抱歉,如果问题标题术语有误,但这是我想做的。我需要对对象 vector 进行排序,但与 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_ 属性为字符串。

最佳答案

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

例如:

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 );
}

关于c++ - STL 容器中的有序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18659882/

相关文章:

algorithm - 该算法的复杂度函数

python - 算法可以更快地为日志文件中的每个电话号码找到合适的前缀?

c# - 在几天内均匀分配元素

java - 查找加起来等于给定字符串的所有子字符串组合

c++ - 对 double 类型的二维 vector 进行 PCA 计算

c++ - 不能用于初始化 const std::string * 类型的实体

c++ - 在 C++ 中将 char[] 数组转换为 LPCTSTR

c++ - WTS连接 session

c++ - 在 C++ 中使用内联汇编对缓冲区中的数字求和

java - 任何用于匹配名称的消歧工具/API?