string - 为什么使用通用 lambda 对字符串向量进行排序不起作用?

标签 string sorting c++17 c++20 stdvector

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool sortByName(const auto& first, const auto& second) {
    return first < second;
}

void print(const auto& vec) {
    for(const auto& s : vec)
    cout << s << ", ";
    cout << endl;
}

int main() {
    vector vec2 = {"sam", "zach", "adam", "peter"};
    print(vec2);

    auto cmp = [](const auto& s1, const auto& s2) {
        return s1 < s2;
    };
    std::sort(vec2.begin(), vec2.end(), cmp);          // line (1)
    print(vec2);

    auto cmp2 = [](const string& s1, const string& s2) {
        return s1 < s2;
    };
    std::sort(vec2.begin(), vec2.end(), cmp2);         // line (2)
    print(vec2);
}

对于上面的代码片段,结果如下,

  1. std::sort 与 cmp2 对向量进行排序,即 {adam, peter, sam, zach,}
  2. std::sort 与 cmp 保持向量元素的顺序与原始向量相同,即 {sam, zach, adam, peter,}

为什么我们必须在 cmp2 中显式提供类型,即“字符串”才能使这种排序工作?

最佳答案

vector vec2 = {"sam", "zach", "adam", "peter"};

这使得vec2进入std::vector<const char*> .

因此,您正在比较 const char*在通用 lambda 中,而不是指针实际指向的内容。

为了使其工作而不转换 const char*发送至std::string s(或更好,std::string_view s),您可以使用 std::strcmp :

#include <cstring>

auto cmp = [](const char* s1, const char* s2) {
    return std::strcmp(s1, s2) < 0;
};

关于string - 为什么使用通用 lambda 对字符串向量进行排序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76652581/

相关文章:

php - 比较 Magento .phtml 文件中的字符串

javascript - jquery-datatables 多列排序方向

JavaScript - 按两个整数属性对数组进行排序

php - 我可以在传递 GET 变量的同时仍然在 PHP 中保留旧的 GET 变量吗

c++ - 如何使用自定义运算符<<创建折叠表达式?

php - 在 php 中从空格切换到制表符分隔

java - 文本是否包含日期格式?

JAVA - 从文本文件中读取,识别新行

c++ - 在 constexpr 构造函数中获取一个特殊的指针值(类似于 "second"nullptr)

c++ - 模板化自动工厂注册