c++ - 使用std:sort对cpp中的字符串数组进行排序

标签 c++ arrays string sorting

我尝试按照this one之类的网站的一些建议对字符串数组(是,而不是 vector )进行排序。这是我到目前为止编写的代码,但是它总是打印出this long错误(在Google上没有结果)。如何解决?

#include <algorithm>
#include <cstring>
#include <iostream>
//qsort(names, n, 15, (int (*)(const void *, const void *))strcmp);



int main()
{
    std::cout << "hi";
    char arr[3][6];
    strcpy(arr[0], "hello"), strcpy(arr[1], "hillo"), strcpy(arr[2], "hallo");
    std::sort(arr, arr + 3, [](char const *lhs,
                           char const *rhs) { return strcmp(lhs, rhs) < 0; });
    //qsort(arr, 3, 20, (int (*)(const void *, const void *))strcmp);
    for (int i = 0; i < 3; ++i)
        std::cout << arr[i] << '\n';
}

最佳答案

这是错误消息的相关部分:

error: array must be initialized with a brace-enclosed initializer


不幸的是,这不是很清楚,但是它来自排序实现内部。因此,让我们修改算法的前提条件:std::sort通过交换元素来实现。因此,它要求元素是可交换的。数组的元素是数组。阵列不可交换。因此,数组数组不可排序。

will using the type "string" work here?


使用std::string将起作用。它是可交换的。您甚至不需要自定义比较功能,因为它甚至具有可比性。

what makes arrays unswappable and other types swappable


交换通过移动初始化(和分配)进行补充。语言规则说数组不能移动初始化(也不能分配)。知道这一点后,看看错误消息是否有意义。

关于c++ - 使用std:sort对cpp中的字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64087239/

相关文章:

c++ - 如何获取 Eigen::MatrixXd 的行数和列数?

c++ - 相互依赖的类模板设计?

c++ - 确定数组分配的长度

c++ - 成员函数返回错误的智能指针

c++ - 关于 C++ 中的 "bind"

c++ - 采用 std::vector 或 std::array 的模板函数

python - 从字典的特定键创建多维numpy数组

string - bash:在多个其他字符串中查找字符串

java - 如何计算字符串中每个字母出现的次数?

string - 您如何检查可选字符串的长度?