multimap
2009-04-22 01:00:07| 分类:
C/C++ | 标签:
|字号大中小 订阅
声明
multimap<string,string> authors;
元素的添加
//adds first element with key Barth
authors.insert(make_pair(string(“Barth, John”),string(“Sot-Weed Factor”)));
//ok: adds second element with keyBarth
authors.insert(make_pair(string(“Barth, John”),string(“Lost in the Funhouse”)));
元素的删除
string search_item(“Kazuo Ishiguro”);
//erase all elements with this key; returnsnumber of elements removed
multimap<string,string>::size_typecnt=authors.erase(search_item);
查找元素
方法1: find count
//author we’ll look for
string search_item(“Alain de Botton”);
//how many entries are there for thisauthor
typedef multimap<string,string>::size_type sz_type;
sz_typeentries=author.count(search_item);
//get iterator to the first entry for thisauthor
multimap<string,string>::iteratoriter=author.find(search_item);
//loop through the number of entries there arefor this author
for(sz_type cnt=0; cnt<entries;++cnt, ++iter)
首先调用count确定某作者所写的书籍数目,然后调用find获得指向第一个该键所关联的元素的迭代器。for循环迭代的次数依赖于count返回的值。在特殊情况下,如果count返回0值,则该循环永不执行。
方法2: lower_bound upper_bound
//definitions of authors and search_item asabove
//beg and end denote range of elements for thisauthor
typedef multimap<string,string>::iterator authors_it;
authors_itbeg=authors.lower_bound(search_item),
//loop through the number of entries there arefor this author
while(beg!=end){
cout<<beg->second<<endl;//printeach title
++beg;
}
在同一个键上调用lower_bound和upper_bound,将产生一个迭代器范围,指示出该键所关联的所有元素。如果该键在容器中存在,则会获得两不同的迭代器:lower_bound返回的迭代器指向该键关联的第一个实例,而upper_bound返回的迭代器则指向最后一个实例的下一位置。如果该键不在multimap中,这两个操作将返回同一个迭代器,指向依据元素的排列顺序该键应该插入的位置。
方法3: equal_range
//definitions of authors and search_item asabove
//pos holds iterators that denote range ofelements ofr this key
pair<authors_it,authors_it>pos=authors.equal_range(search_item);
//loop through the number of entries there arefor this author
while(pos.first!=pos.second){
}
pair对象的first成员存储lower_bound函数返回的迭代器,而second成员则记录upper_bound函数返回的迭代器。
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef struct employee
{
//Member Function
public:
//Attribute
public:
}employee;
//创建multimap的实例,整数(职位编号)映射员工信息
typedef multimap<int, employee>EMPLOYEE_MULTIMAP;
typedef multimap<int,employee>::iteratorEMPLOYEE_IT;
typedef multimap<int,employee>::reverse_iteratorEMPLOYEE_RIT;
employee::employee(long eID, string e_Name, floate_Salary)
//函数名:output_multimap
//函数功能:正向输出多重映射容器里面的信息
//参数:一个多重映射容器对象
void output_multimap(EMPLOYEE_MULTIMAP employ)
{
}
//函数名:reverse_output_multimap
//函数功能:逆向输出多重映射容器里面的信息
//参数:一个多重映射容器对象
void reverse_output_multimap(EMPLOYEE_MULTIMAP employ)
{
}
int main(int argc, char *argv[])
{
}