#include<iostream>
#include<string>
#include<map>
using namespace std;

int main() 
...{
map<string,int> strint;
strint.insert(make_pair("Banana",1));
strint["Apple"]=2;
strint.insert(map<string,int>::value_type("Grape",3));
typedef map<string,int>::value_type valtype;
strint.insert(valtype("Pear",4));
strint.insert(valtype("Watermelon",5));
for(map<string,int>::iterator iter=strint.begin();iter!=strint.end();++iter)
...{
cout<<(*iter).first<<" "<<(*iter).second<<endl;
}
string ask;
while(cin>>ask)
...{
switch(strint[ask])
...{
case 1:
cout<<"The input is "<<ask<<endl;
break;
case 2:
cout<<"The input is "<<ask<<endl;
break;
case 3:
cout<<"The input is "<<ask<<endl;
break;
case 4:
cout<<"The input is "<<ask<<endl;
break;
case 5:
cout<<"The input is "<<ask<<endl;
break;
case 0:
default:
cout<<"The input is the other: "<<ask<<endl;
}
}
return 0;
} 
以前知道用switch case语句对于多个的分支处理很好。但是只能是整形的数据。想下有很多情况下用不了的。我也有就这个问题在论坛上问过,但都没有人给出一个程序,只是说了一大堆,不过也没有说到我今天用的方法。其实真是一个好的方法,不过可能会随着输入的增多而占用大量空间。如里是这个的话还可以用m.cout()先处理一下。
本文通过一个具体的 C++ 程序示例介绍了如何使用 std::map 容器来存储字符串到整数的映射,并演示了如何遍历 map 以及如何根据输入的字符串查找对应的整数值。
1313

被折叠的 条评论
为什么被折叠?



