51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 2964|回复: 4
打印 上一主题 下一主题

请教C++高手们,可以给小女子解释一下map使用实例的代码吗

[复制链接]

该用户从未签到

1#
发表于 2013-8-5 15:49:35 | 显示全部楼层
本帖最后由 yun@123 于 2013-8-5 15:52 编辑

#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
        map<int, string> mapstudent;
        pair<map<int, string>::iterator, bool> Insert_Pair;

        Insert_Pair = mapstudent.insert(pair<int, string>(1, "student_one"));//向mapstudent和Insert_Pair的key=1赋值,赋值成功Insert_Pair.second为true,否则为false
        if(Insert_Pair.second == true)
        {
                cout<<"Insert Successfully"<<endl;
        }
        else
        {
                cout<<"insert failure"<<endl;
        }

        Insert_Pair = mapstudent.insert(pair<int, string>(1, "student_two"));//因为上面已经对key=1进行过赋值,故再次使用此方法无法覆盖原来的,即赋值失败返回false,若想要覆盖原来的可以通过operator[]进行赋值,即mapstudent[1]="student_two",当然也可能是由于你手误将mapstudent.insert(pair<int, string>(1, "student_two"));里面写成1,改成其他值就可以了
        if(Insert_Pair.second == true)
        {
                cout<<"Insert Successfully"<<endl;
        }
        else
        {
                cout<<"Insert Failure"<<endl;
        }

        map<int, string>::iterator iter;
        for(iter = mapstudent.begin(); iter != mapstudent.end(); iter++)//输出mapstudent中所有元素的值
        {
                cout<<iter->first<<"   "<<iter->second<<endl;
        }
        cin.get();
        return 0;
}
即你的这个代码第一次赋值是成功的,返回true,第二次赋值失败,返回false,故输出结果就是你说的那种喽
回复 支持 反对

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-5-13 21:17 , Processed in 0.063893 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表