为什么std::max传入字符串字面量报错而std::string变量正常?
报错原因
- 第一种调用传入的是两个类型完全一致的
std::string变量,std::max会调用std::string重载的比较运算符按字典序比对内容,运行逻辑正常。 - 第二种调用传入的是字符串字面量,C++中字符串字面量的类型是
const char[N],N是字符串长度+1(包含结尾\0),所以"abc"的类型是const char[4]、"abcd"的类型是const char[5],二者属于不同类型。模板函数std::max要求两个入参类型一致才能推导出统一的模板参数T,类型不匹配直接触发编译报错。
即使你强制把两个字面量都转成const char*让编译通过,运行结果也不符合预期:此时std::max比对的是两个指针的内存地址大小,不是字符串的实际内容。
修复方案
你可以任选以下一种方案修复代码:
- 显式将字符串字面量转换为
std::string类型
#include<bits/stdc++.h> using namespace std; int main() { // Case 1 string str1 = "abc", str2 = "abcd"; cout << max(str1, str2) << endl; // Case 2 修复后 cout << max(string("abc"), string("abcd")) << endl; return 0; }
- 使用C++14及以上版本支持的
std::string字面量后缀s
#include<bits/stdc++.h> using namespace std; using namespace std::literals::string_literals; int main() { // Case 1 string str1 = "abc", str2 = "abcd"; cout << max(str1, str2) << endl; // Case 2 修复后 cout << max("abc"s, "abcd"s) << endl; return 0; }
- 显式指定
std::max模板参数,配合strcmp实现字符串内容比较
#include<bits/stdc++.h> using namespace std; int main() { // Case 1 string str1 = "abc", str2 = "abcd"; cout << max(str1, str2) << endl; // Case 2 修复后 cout << max<const char*>("abc", "abcd", [](const char* a, const char* b) { return strcmp(a, b) < 0; }) << endl; return 0; }
内容的提问来源于stack exchange,提问作者Yuvraj Parashar
相关产品推荐
相关产品推荐

