排序 std::vector<std::pair<std::string,bool>>通过字符串?

2021-12-10 00:00:00 sorting vector c++ stl std-pair

如何通过比较作为 std::stringpair.first 来对这个 vector 进行排序?(不提供静态比较函数,也不使用 boost).

How can I sort this vector by comparing the pair.first which is an std::string? (without providing a static compare function, nor use boost).

推荐答案

std::vector<std::pair<std::string, bool> > v;
std::sort(v.begin(), v.end());

std::pair 重载 operator< 先按 first 元素排序,然后按 second 元素排序.因此,如果您仅使用默认排序顺序 (operator<) 对 vector 进行排序,您将获得所需的排序.

std::pair overloads operator< to sort first by the first element then by the second element. Thus, if you just sort the vector using the default sort ordering (operator<), you'll get your desired ordering.

相关文章