map_set
来源:互联网 发布:嘉靖和万历知乎 编辑:程序博客网 时间:2024/06/01 20:34
std::map
template
STL map
1、map的使用
map的底层是红黑树
insert参数类型:pair类型(两个)
erase可以删除一个位置(通过find找到迭代器)还可以删除迭代器区间
pair参数:1(key_type:第一个参数) 2(mapped_type:第二个参数)
遍历需要迭代器
TreeIterator{ Node* node;}Node* node;pair<K,V>& operator*(){ return node->kv;}pair<K,V>* operator->(){ return &(operator*())}
#include<map>#include<set>#include<string>void Testmap(){ string strs[] = {}; map<string,int>countMap; countMap.insert(pair<string,int>"苹果",1); countMap.insert(pair<string,int>"苹果",2); countMap.insert(pair<string,int>"苹果",3); //统计个数 for (size_t i = 0;i < sizeof(strs)/sizeof(strs[0]);++i) { 第一种 //取到迭代器 map<string,int>::iteratot ret = countMap.find(strs[i]); if(ret != countMap.end()) { (*ret).second++; //ret->second++; } else { //make_pair是一个模板函数 countMap.insert(make_pair(strs[i],1)); //countMap.insert(pair<string,int>(strs[i],1)); } }
template
//第二种 /insert返回bool值,两种情况,成功or失败,如果成功,迭代器指向新插入位置,失败迭代器指向和插入元素Key相等的位置。 pair<map<string,int>::iterator,bool> kvRet= countMap.insert(pair<string,int>(strs[i])); if(kvRet.second == false) { kvRet.first->second++; }
//第三种 countMap[strs[i]]++; //实现了一个operator[],operator[]可以插入,也可以修改。
map<string,int>::iterator it = countMap.begin(); while(it != countMap.end()) { //取key或者value cout<<(*it).first<<":"<<(*it).second; ++it; } cout<<endl; map<string,string> dict; dict.insert(make_pair("left","左边")); //插入 dict["left"] = "剩余"; //修改 dict["right"] = "右边"; //插入 ``` ==map的删除== ``` 1、删除一个位置 typedef map<sting,string> Dict; typedef map<sting,string>::iterator DictIt; dict.erase("left"); DictIt dIt = dict.find("right"); if(dIt != dict.end()) dicr.erase(dIt);2、删除一个迭代器区间 typedef map<int,string> SortMap; typedef map<int,srting>::iterator SortMapIt; SortMap sm sm[1] = "榴莲"; sm[4] = "西瓜"; sm[3] = "樱桃"; sm[2] = "苹果"; SortMap SIt = sm.begin(); while(sIt != sm.end()) { cout<<sIt->first<<":"<<sIt->second<<endl; ++sIt; } //结果按照数字排列 //删除编号大于3. SortMapIt pos = sm.find(3); if (pos != sm.end()) { sm.erase(pos,sm.end()); } SortMap SIt = sm.begin(); while(sIt != sm.end()) { cout<<sIt->first<<":"<<sIt->second<<endl; ++sIt; }}
2、pair类型
两个类型,map是二叉搜索树,所以Key不能被修改,所以是const类型。Key的名字叫做first
template<class Key,const V>struct pair{ const Key first; V second}
Std::set
STL set
template
1、set的使用
set的底层是红黑树,
insert参数类型:两个都是key_type类型的。
void TestSet(){ set<string> names; names.insert("LL"); names.insert("LLL"); names.insert("XX"); if(names.insert("XL") == 0) { names.insert("XL"); }}
其中Key是用来判断插入数据是否存在。
map和set的异同
map
1、通过key找value 2、key排序
set
1、判断key存在不存在2、排序3、set过滤(去重)