即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

STL 中的map和multimap

编程语言 gyc840067702 7℃ 0评论

映射(map

/*
*STL 测试
*map and multimap 映射和多重映射
*/
#include 
#include 
#include 
typedef std::string str;
typedef std::map<char, int, std::less<char>> CIMAP;
typedef std::multimapstd::less> SSMMAP;
typedef std::pair sspair;

int main()
{
    //map1 char为键类型,int为值类型  map会自动排序(依据less)
    CIMAP map1;
    CIMAP::iterator it;
    //初始化map1
    map1['c'] = 3;
    map1['d'] = 4;
    map1['a'] = 1;
    map1['b'] = 2;
    map1.insert(CIMAP::value_type('e',5)); //map1.inser(std::pair('e',5));
    //输出map1 ,first对应char,second对应int
    std::cout<<" map1.char -- map1.int :"<<std::endl;
    for(it = map1.begin(); it != map1.end(); it++)
        std::cout<<" "<< (*it).first <<": "<< (*it).second <<"\n";
    //检索d键对应的值
    CIMAP::const_iterator ptr;
    ptr = map1.find('d');
    std::cout<< (*ptr).first <<"键对应的值:"<<(*ptr).second <<std::endl;

    //定义多重映射
    SSMMAP mulmap;
    SSMMAP::iterator mulit;
    mulmap.insert(sspair("Computer ","can surf the Internet."));
    mulmap.insert(sspair("Computer ","can play games."));
    mulmap.insert(sspair("Computer ","can shop."));
    mulmap.insert(sspair("smartphone ","also can surf the Internet."));
    mulmap.insert(sspair("smartphone ","also can play games."));
    //输出mulmap
    for(mulit = mulmap.begin(); mulit != mulmap.end(); mulit++)
        std::cout<< (*mulit).first << (*mulit).second <<std::endl;
    //检索并输出Computer键所对应的所有值
    std::cout<<"find Computer: "<<std::endl;
    mulit = mulmap.find(str("Computer "));
    while((*mulit).first =="Computer "){
        std::cout<< (*mulit).first << (*mulit).second <<std::endl;
        mulit++;
    }
    return 0;
}

注:编译环境为Qtcreator

转载请注明:CodingBlog » STL 中的map和multimap

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情