如何避免长if语句,根据用户输入调用对应vector对象?
如何在C++中通过字符串输入直接映射到对应vector(避免大量if语句)
我正在编写一个C++程序,希望接收用户输入的字符串后直接调用对应的vector,不想写一大堆if语句。比如输入"silver"就直接调用名为silver的vector,程序要处理很多颜色对应的vector,逐个写if太繁琐,有没有可行的实现方式?
代码示例:
#include <iostream> #include "cmath" #include <vector> using namespace std; int main() { string color1; vector<double> gold = {0, 0, pow(10, -1), .95, 1.05}; vector<double> silver = {0, 0, pow(10, -2), .9, 1.10}; cout << "input color:"; cin >> color1; return 0; }
你可以用**哈希表(std::unordered_map)**或者有序映射(std::map)来建立字符串和vector的关联,这样就能通过输入的字符串直接查找到对应的vector,完全不用写一堆if-else。
实现步骤:
- 引入
<unordered_map>头文件(如果用std::map则引入<map>) - 创建一个映射容器,键是颜色字符串,值是对应vector的引用(或指针,避免拷贝开销)
- 将所有颜色vector和对应的字符串存入映射
- 根据用户输入的字符串查找映射,找到后直接使用对应的vector
修改后的代码示例:
#include <iostream> #include <cmath> #include <vector> #include <unordered_map> // 引入哈希表头文件 using namespace std; int main() { string color1; vector<double> gold = {0, 0, pow(10, -1), .95, 1.05}; vector<double> silver = {0, 0, pow(10, -2), .9, 1.10}; // 创建字符串到vector引用的哈希映射 unordered_map<string, vector<double>&> colorMap; colorMap["gold"] = gold; colorMap["silver"] = silver; cout << "input color:"; cin >> color1; // 查找输入对应的vector auto it = colorMap.find(color1); if (it != colorMap.end()) { // 找到对应的vector,这里可以直接使用it->second cout << "Found vector for " << color1 << ":" << endl; for (double val : it->second) { cout << val << " "; } cout << endl; } else { cout << "Color not found!" << endl; } return 0; }
注意事项:
- 如果vector是在函数内部定义的(比如main里),用引用没问题,因为map的生命周期和vector一致;如果vector是动态创建的,建议用指针存储,避免悬空引用。
- 新增颜色时只需在map里添加一行映射,无需修改判断逻辑,扩展性极强。
- 必须处理输入不存在的情况,用
find方法判断迭代器是否等于end()即可。 - 如果需要忽略大小写匹配(比如输入"Silver"也能触发silver的vector),可以在存入map和处理输入时统一转成小写(或大写)。
内容的提问来源于stack exchange,提问作者Pozu
相关产品推荐
相关产品推荐

