multimap和map的区别:

首先认识一下multimap和map的区别:

1>        multimap不提供operator[ ]运算符。因为这个运算符的语义在同一个键可以保存多个值的容器multimap里是无意义的。

2>        multimap插入元素的时候总是能成功的。所以插入insert()方法只返回一个iterator。不像是map的insert()返回的是《iterator , bool》.

麻烦的是multimap查找元素的时候,因为这里不提供operator[ ],而find(key)返回的可能是多个元素,这也不准确。但是multimap提供了lower_bound()和upper_bound()函数;

分别返回的是同一个健的第一个元素得迭代器和最后一个元素得下一个元素得迭代器。注意的是,如果没有这个键值,则lower_bound和upper_bound是相同得;还有一个方法就是使用equal_bound()方法。这个函数返回的是两个iterator得std::pair<>(分别是lower_bound()和upper_bound()得迭代器);

#include <iostream>
#include <map>
#include <utility> //utility是实用性工具类得意思
#include <list> class Buddylist
{
public:
void addBuddy(const std::string &name , const std::string &buddy);
bool isBuddy(const std::string &name , const std::string &buddy);
void delBuddy(const std::string &name , const std::string &buddy);
std::list<std::string> getBuddies(const std::string &name) const; private:
std::multimap<std::string , std::string> mBuddies;
}; void Buddylist::addBuddy(const std::string &name , const std::string &buddy)
{
if(!isBuddy(name,buddy))
{
mBuddies.insert({name,buddy});
}
}
bool Buddylist::isBuddy(const std::string &name , const std::string &buddy)
{
auto iter = mBuddies.equal_range(name); //返回的是key = name得这个范围的所有得值对应的迭代器
auto Beg = iter.first; //这些元素的首迭代器
auto End = iter.second; //最后元素得后一个得迭代器
for(;Beg != End;++Beg)
{
if(Beg->second == buddy)
{
return true;
}
}
return false; }
void Buddylist::delBuddy(const std::string &name , const std::string &buddy)
{
auto Beg = mBuddies.lower_bound(name);
auto End = mBuddies.upper_bound(name);
while(Beg != End)
{
if(Beg->second == buddy)
{
mBuddies.erase(Beg);
break;
}
++Beg;
}
}
std::list<std::string>Buddylist::getBuddies(const std::string &name) const
{
auto range = mBuddies.equal_range(name);
auto Beg = range.first;
auto End = range.second;
std::list<std::string> mNameList;
while(Beg != End)
{
mNameList.push_back(Beg->second);
++Beg;
}
return mNameList;
}
int main()
{
Buddylist buddy1,buddy2;
std::list<std::string> list_1,list_2;
buddy1.addBuddy("list_1","wenjie");
buddy1.addBuddy("list_1","meijun");
buddy1.addBuddy("list_1","taoge");
buddy1.addBuddy("list_1","dajun"); buddy1.delBuddy("list_1","taoge");
list_1 = buddy1.getBuddies("list_1");
for(auto &iter : list_1)
{
std::cout << "list_1 : " << iter << std::endl;
} buddy2.addBuddy("list_2","abcd");
buddy2.addBuddy("list_2","fefg");
buddy2.addBuddy("list_2","jhnf");
buddy2.addBuddy("list_2","errh"); list_2 = buddy2.getBuddies("list_2");
for(std::list<std::string>::iterator iter = list_2.begin();
iter != list_2.end();++iter)
{
std::cout << "list_2 : " << *iter << std::endl;
} return ;
}

结果是:

list_1 : wenjie
list_1 : meijun
list_1 : dajun
list_2 : abcd
list_2 : fefg
list_2 : jhnf
list_2 : errh

05-12 07:38