C++ map

map :键值对
map<int,string> m;
mp.insert(make_pair(1,“faith1”));
mp.insert(pair<int,string>(3,“faith3”));
mp.insert(map<int,string>::value_type(2,“faith2”));
mp[4] = “faith4”;

insert是函数,其返回值可以判断是否插入成功
[]运算符重载:如果数据存在,则覆盖原有的值,如果数据不存在,则插入一条新的数据

multimap:允许键重复

#include <iostream>
#include <set>
#include <map>
#include <string>
using namespace std;
void fun1()
{
    set<int> s;
    s.insert(1);
    std::pair<set<int>::iterator,bool> ret = s.insert(3);
    if(ret.second)
        cout<<"插入成功"<<*(ret.first)<<endl;
    else
        cout<<"插入失败"<<endl;
}
void fun2()
{
    set<int> s;
    s.insert(1);
    s.insert(3);
    s.insert(5);
    s.insert(2);
    s.insert(6);
    s.insert(8);
//    set<int>::iterator it = s.find(11);
//    if(it!=s.end())
//        cout<<"找到"<<endl;
//    else
//        cout<<"未找到"<<endl;


//     set<int>::iterator it = s.lower_bound(12);
//     cout<<*it<<endl;


     set<int>::iterator it = s.upper_bound(17);
     if(it!=s.end())
         cout<<*it<<endl;
     else
         cout<<"未找到"<<endl;

}
void fun3()
{
    multiset<int> s;
    s.insert(1);
    s.insert(1);
    s.insert(1);
    s.insert(1);
    s.insert(3);
    s.insert(5);
    s.insert(2);
    s.insert(6);
    s.insert(8);
    std::pair<multiset<int>::iterator,multiset<int>::iterator> it = s.equal_range(3);
    multiset<int>::iterator it1 = it.first;
     multiset<int>::iterator it2 = it.second;

     while(it1!=it2)
     {
         cout<<*it1<<endl;
         it1++;
     }


}
void print(map<int,string> &mp)
{
    map<int,string>::iterator it = mp.begin();
    while(it!=mp.end())
    {
        cout<<"id :"<<it->first<<"name :"<<it->second<<endl;
        it++;
    }
}

void fun4()
{
    map<int,string> mp;
    mp.insert(make_pair(1,"faith1"));
    mp.insert(pair<int,string>(3,"faith3"));
    mp.insert(map<int,string>::value_type(2,"faith2"));

    mp[4] = "faith4";
    //mp.erase(mp.begin());
    print(mp);
}
void printm(multimap<string,int> &mp)
{
    multimap<string,int>::iterator it = mp.begin();
    while(it!=mp.end())
    {
        cout<<"id :"<<it->second<<"name :"<<it->first<<endl;
        it++;
    }
}

void fun5()
{
    multimap<string,int> mp;
    mp.insert(make_pair("faith1",1));
    mp.insert(make_pair("faith1",1));
    mp.insert(make_pair("faith1",1));
    mp.insert(make_pair("faith1",1));
    printm(mp);
}

int main1(int argc, char *argv[])
{
   //fun1();
   //fun2();
    //fun3();
    //fun4();
    fun5();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值