原理:map 是关联容器,K/V形式存储,K起到索引的作用,V则表示与索引相关联的数据,以红黑树的结构实现,
插入和删除等操作都可以在O(lgN)时间内完成。
insert插入成功返回true,否则是false
插入和删除等操作都可以在O(lgN)时间内完成。
set是关联容器,set中每个元素都只包含一个关键字,set每个元素的值必须是唯一的
应用:使用map 统计水果次数
方法一:使用find(),find若是找到了就返回一个 iterator to it ,否则返回an iterator to map::end
//for(size_t i = 0; i<sizeof(strs)/sizeof(strs[0]);++i)
//{
// map<string,int>::iterator it = countMap.find(strs[i]);
// /*find若是找到了就返回一个 iterator to it ,否则返回an iterator to map::end */
// if(it!=countMap.end())
// {
// it->second++;//找到了则++
// //(*it).second++;
// }
// else
// {
// countMap.insert(pair<string,int>(strs[i],1));
// }
//}
方法二:使用Insert,The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same key existed.
insert插入成功返回true,否则是false
//for(size_t i = 0; i<sizeof(strs)/sizeof(strs[0]);++i)
//{
// pair<map<string,int>::iterator,bool> ret;
// ret = countMap.insert(pair<string,int>(strs[i],1));
// //The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same key existed.
// //insert插入成功返回true,否则是false
// if( ret.second = false)
// {
// ret.first->second++;
// }
//}
方法三:
countMap[strs[i]]++;//(*((this->insert(make_pair(x,T()))).first)).second
完整代码:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
#include<map>
int main()
{
string strs[10]={"西瓜","苹果","草莓","苹果","苹果","草莓","草莓","草莓","西瓜","苹果"};
map<string,int> countMap;
//方法—
//for(size_t i = 0; i<sizeof(strs)/sizeof(strs[0]);++i)
//{
// map<string,int>::iterator it = countMap.find(strs[i]);
// /*find若是找到了就返回一个 iterator to it ,否则返回an iterator to map::end */
// if(it!=countMap.end())
// {
// it->second++;//找到了则++
// //(*it).second++;
// }
// else
// {
// countMap.insert(pair<string,int>(strs[i],1));
// }
//}
//方法二
//for(size_t i = 0; i<sizeof(strs)/sizeof(strs[0]);++i)
//{
// pair<map<string,int>::iterator,bool> ret;
// ret = countMap.insert(pair<string,int>(strs[i],1));
// //The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same key existed.
// //insert插入成功返回true,否则是false
// if( ret.second = false)
// {
// ret.first->second++;
// }
//}
//方法三
/*for(size_t i = 0; i<sizeof(strs)/sizeof(strs[0]);++i)
countMap[strs[i]]++;*///(*((this->insert(make_pair(x,T()))).first)).second
vector<map<string,int>::iterator> v;//拿出排名靠前的水果
map<string,int>::iterator CountIt = countMap.begin();
while(CountIt != countMap.end())
{
v.push_back(CountIt);
++CountIt;
}
struct Compare
{
bool operator()(map<string,int>::iterator l ,map<string,int>::iterator r)
{
return l->second > r->second;
}
};
sort(v.begin(),v.end(),Compare());
getchar();
return 0;
}