map插入数据

来源:互联网 发布:拍照软件mix 编辑:程序博客网 时间:2024/06/06 09:31
#include <string>#include <iostream> #include <map> #include <utility> using namespace std;int main(){    map<int, string> Employee;    //通过键值赋值    Employee[123] = "Mayuefei";    //通过成员函数insert和STL的pair赋值    Employee.insert(pair<int, string>(132, "Liaoyuanqing"));    //通过value_type赋值    Employee.insert(map<int, string>::value_type(124, "Liyiyi"));    //通过make_pair赋值    Employee.insert(make_pair(234, "LLK.D"));    for (map<int, string>::iterator it = Employee.begin(); it != Employee.end(); it++)    {       cout<<(*it).first<<":"<<(*it).second<<endl;//取值操作    }    system("pause");    return 1;};

map的下标操作符,支持元素的直接存取
索引可以是任意型别,而非局限为整数型别。
如果你使用某个key作为索引,而容器之中尚未存在对应元素,那么会自动安装安插该元素。
用map[index]的方式插入数据比一般的插入方式,原因是,新元素必须先使用default构造函数将实值(value)初始化,而这个初值马上又被真正的value给覆盖了。

0 0