我正在尝试做一个对 3 个元素进行排序的模板函数,
numbers(int, double) 工作正常但字符串的行为不符合预期
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
template<typename TYPE>
void sort3(TYPE n1, TYPE n2, TYPE n3) {
TYPE arr[3];
arr[0] = n1;
arr[1] = n2;
arr[2] = n3;
sort(arr, arr + 3);
for (int i = 0; i < 3; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main(int argc, char** argv) {
sort3("B", "Z", "A");
sort3(10.2, 99.0, 1.9);
sort3(200, 50, 1);
return 0;
}
给我以下输出:
A Z B
1.9 10.2 99
1 50 200
根据我的理解 sort3("B", "Z", "A");
应该给我 A B Z
它不是特定于操作系统的,因为它在 online compiler 中给出了相同的结果
那里发生了什么?
最佳答案
那是因为您传递的是字符串字面量,即字符数组。当将它们作为参数传递给函数时,数组会衰减为指针。因此,您要排序的是这些指针的值(而不是它们指向的字符串)。
试试这个:
#include <string>
// ...
sort3(std::string("B"), std::string("Z"), std::string("A"));
之所以有效,是因为 operator <
的过载对于 std::string
存在,并且 std::sort
使用 operator <
在自定义比较器未作为第三个参数传递时比较元素(这是您的情况)。
关于c++ - 与模板方法不一致的字符串排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131934/