C++ map 基本操作

#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>

using namespace std;

typedef map<string,long long> URL_COUNT;

//map的打印
void print(URL_COUNT url_count){
        for(map<string,long long>::iterator i = url_count.begin(); i!=url_count.end(); i++){
                cout << i->first << " " << i->second <<endl;
        }
}
 
void print_ele(map<string,long long>::iterator ele){
        cout << ele->first << "=>" << ele->second << endl;
}

int main(){

        //map的建立
        URL_COUNT url_count;

        //************************************************************
        //map的插入
        //map[key] = value
        url_count["a"] = 1;
        url_count["b"] = 2;
        url_count["c"] = 3;

        //insert(map<string,long long>::value_type(key,value))
        url_count.insert(map<string,long long>::value_type("e",5));

        //insert(make_pair(key,value))
        url_count.insert(make_pair("f",6));

        //insert(pair<string,int> p)
        pair<string, int> p;
        p.first = "g";
        p.second = 7;
        url_count.insert(p);

        //不正确的插入方式
        //url_count.insert("d",4);

        print(url_count);

        //*************************************************************
        //map的查找
        //count函数只返回0或者1
        cout << url_count.count("e") << endl;
        cout << url_count.count("s") << endl;

        //find函数返回key对应的对象的迭代器
        print_ele(url_count.find("f"));
        //没有找到时返回Segmentation fault,慎用
        //print_ele(url_count.find("s"));

        //*************************************************************
        //map的删除
        //erase(key),有则删除返回1,无则返回0
        cout << url_count.erase("f") << endl;

        //erase(指向map元素的迭代器)
        map<string,long long>::iterator i = url_count.find("g");
        url_count.erase(i);

        print(url_count);

        return 0;
}


返回结果:

a 1
b 2
c 3
e 5
f 6
g 7
1
0
f=>6
1
a 1
b 2
c 3
e 5


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值