您的位置:首页 > 编程语言 > C语言/C++

stl之map使用.cpp

2017-01-05 23:02 337 查看
/*标准模板库(stl)之映射(map)
 *map提供一对一映射,其中第一个键值为主键,不能重复
 *map按照主键自动排序
 */
#include <iostream>
#include <map>
using namespace std;

int main()
{         
//定义模板类对象并插入元素
    map<string, string> words;
    words.insert(pair<string,string>("friend", "朋友"));
    words.insert({"good", "非常好"});
    pair<string,string> a("and", "并且");//定义一个pair对象插入map
    words.insert(a);
    words.insert({"good", "好"});
    words["you"] = "你";//如果有无此映射则添加,如果有则改变
    words["friend"] = "哥们";

    cout << "查看 good : " << words["good"] << endl;
    cout << "查看 yes  : " << words["yes"] << endl;//这里没有yes这个key,所以返回为空
//使用迭代器遍历
    cout << "--------------" << endl;
    for (auto it=words.begin(); it!=words.end(); it++) {
        cout << it->first << " : " << it->second << endl;
    }
//使用迭代器遍历
    map<string ,string>::iterator it = words.find("good");
    if (it != words.end()) {
        cout << "map is : "  << it->second << endl;
    } else {
        cout << "没找到" << endl;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: