STL.map数据插入的方式及差异

本文通过三种不同方式展示了如何使用 C++ 中的 map 容器进行数据插入操作,并对比了不同插入方法的特点。包括使用 insert 函数插入 pair 和 value_type 数据,以及采用数组方式直接赋值。

//唯一性检查或重复就覆盖(新值替旧值)

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


void DispMap(map<int, string>& mpStu)
{
    cout << "Begin****************************************************" << endl;
    for(map<int, string>::iterator it = mpStu.begin(); it != mpStu.end(); it ++){
        cout << it->first << " : " << it->second << endl;
    }
    cout << "End****************************************************" << endl << endl;
}
//用insert函数插入pair数据
void MapTst1()
{
    //进行主键唯一性检查:如果存在,插入失败
    map<int, string> mapStudent;
    mapStudent.insert(pair<int, string>(1, "student_one"));
    mapStudent.insert(pair<int, string>(1, "student_two"));
    mapStudent.insert(pair<int, string>(3, "student_three"));
    DispMap(mapStudent);
}

//用insert函数插入value_type数据
void MapTst2()
{
    //进行主键唯一性检查:如果存在,插入失败
    map<int, string> mapStudent;
    mapStudent.insert(map<int, string>::value_type (1, "student_one"));
    mapStudent.insert(map<int, string>::value_type (1, "student_two"));
    mapStudent.insert(map<int, string>::value_type (3, "student_three"));
    DispMap(mapStudent);
}

//用数组方式插入数据
void MapTst3()
{
    //不进行主键唯一性检查:如果存在,覆盖之前的键值
    map<int, string> mapStudent;
    mapStudent[1] =  "student_one";
    mapStudent[1] =  "student_two";
    mapStudent[3] =  "student_three";
    DispMap(mapStudent);
}


void main()
{
    cout << "Way1 : 用insert函数插入pair数据" << endl;
    MapTst1();
    cout << "Way2 : 用insert函数插入value_type数据" << endl;
    MapTst2();
    cout << "Way3 : 用数组方式插入数据" << endl;
    MapTst3();

}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值