C++中的映射map——小示例

1、根据key值取value值的方法,和数组根据下标取值一个方法,amap[key]

2、根据value取key值,用迭代器从amap.begin()到amap.end()一一遍历,比对iter->second 与 value是否相等

3、以下就是一个小例子

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

int main(){

    string str;
    map<string, int> amap;
    while(1){
        cout<<"输入字符串:";
        cin>>str;
        if(str == "QUIT"){
            break;
        }
        int counter = amap.count(str);
        
        if(counter > 0){
            cout<<str<<"在映射中曾经出现过"<<counter<<"次"<<endl;
            cout<<str<<"您已经输入过"<<amap[str]<<"次"<<endl;
            amap.insert(map<string, int>::value_type(str, ++amap[str]));
        }else{
            cout<<str<<"在映射中没有出现过"<<endl;
//            amap.insert(make_pair(str, 1));
            amap.insert(map<string, int>::value_type(str, 1));
        }
    }
	return 0;
}
发布了82 篇原创文章 · 获赞 71 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/m0_37738114/article/details/105059315