我尝试按照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/