c++用map,创建类似于python中的字典

7 篇文章 1 订阅

1.创建

#include <map>
#include <string>
#include <iostream>

using namespace std;
int main() {
    /*using std::map;
    using std::string;
    using std::cout;*/

    map<string, string> myMap1 = {
        {"Name", "ClearLove"},
        {"Gender", "Male"},
        {"Position", "Jungle"},
        {"ID", "1"}
    };

    map<string, string> myMap2;
    myMap2["Name"] = "TheShy";
    myMap2["Gender"] = "Male";
    myMap2["Position"] = "Top";
    myMap2["ID"] = "2";

    map<string, string> myMap3(myMap2.begin(), myMap2.end());
    myMap3["ID"] = "3";

    map<string, string> myMap4(myMap3);
    myMap4["ID"] = "4";

    map<string, string> mapArr[4] = { myMap1, myMap2, myMap3, myMap4 };

    map<string, string>::iterator iter;//这种方法能够取出保存在map容器里面的数据

    for (int iMap = 0; iMap < 4; iMap++) {
        cout << "Map " << iMap + 1 << " of 4\n";
        for (iter = mapArr[iMap].begin(); iter != mapArr[iMap].end(); iter++) {
            cout << "key: " << iter->first << " , value: " << iter->second << ".\n";
        }
    }
    return 0;
}




#include <map>
#include <string>
#include <iostream>

using namespace std;
int main() {

    map<int, int> dict1;
    dict1[0] = 1;
    dict1[1] = 2;
    dict1[10] = 10;

    map<int, int>::iterator iter;
    iter = dict1.begin();
    while (iter != dict1.end()) {
        cout << iter->first << " : " << iter->second << endl;
        iter++;
    }
    //取出值的方法
    int a = dict1[0];
    cout << a << endl;

    cout << "usually:" << dict1.at(0) << endl;


    map< int,int >::iterator myIter = dict1.find(0);
    cout << myIter->first << "key<-::->value" << myIter->second << endl;

}

2.修改和增加

#include <map>
#include <string>
#include <iostream>
int main()
{
    map<int , string>dict1;
    for(int i = 0;i<=4;i++)
    {
        dict1[i]="hello world";
        cout<<dict1[i]<<endl;
    }
    cout<<"++++++++++++++++++++"<<endl;
    
    //修改 
    string a;
    a = "12345678";
    dict1[0] =a;
    for(int i = 0;i<=4;i++)
    {
        cout<<dict1[i]<<endl;
    }
    dict1[5]="12366";
    cout<<dict1[5]<<endl; 
    
    //增加 
    cout<<"++++++++insert++++++++++++"<<endl;
    dict1.insert(pair<int,string>(9,"insert")) ;
    cout<<dict1[9]<<endl;
    
    
    //删除
    cout<<"+++++++++erase+++++++++++"<<endl;
    dict1.erase(2);
    for(int i = 0;i<=9;i++)
    {
        cout<<dict1[i]<<endl;
    }
 
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

如鸿毛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值