#include <iostream>
#include <string>
using namespace std;
// 哈希函数,将字符串转换为整数
constexpr int hashFunc(const char* str) {
int hash = 0;
for (int i = 0; str[i] != '\0'; i++) {
hash += str[i];
}
return hash;
}
int main() {
string str = "hello";
int choice = hashFunc(str.c_str());
switch (choice) {
case hashFunc("hello"):
cout << "Hello World!" << endl;
break;
case hashFunc("goodbye"):
cout << "Goodbye World!" << endl;
break;
default:
cout << "Unknown input!" << endl;
break;
}
return 0;
}
主要用到的思想是将string用哈希函数转化成int。
在 C++ 中,switch 语句中 case 标签后面的表达式必须是常量值,因此无法直接在 case 标签中使用函数返回值。但是,可以使用常量表达式来实现这个目的,常量表达式是在编译时就能确定其值的表达式。
**
重点
哈希函数改为接受 const char 类型的参数,并使用 constexpr 关键字将其转换为常量表达式*。然后,在 switch 语句中,我们可以使用常量表达式来比较字符串,实现了字符串的 case 选择。
链接: C++中文参考手册constexpr详解