映射(map)

1)逻辑模型:一一对应,键(信息索引)值(信息内容)对,用于信息检索,检索性能可以对数级(O(logN))。
2)物理模型:平衡有序二叉树,又名红黑树。
5 4 3 2 1
5
4
3
2
1
3
2 4
1 5
3)键必须是唯一的。
4)迭代过程实际上是关于键的中序遍历(L-D-R),键升序。
5)存储单位是由键和值组成的pair。
template<typename FIRST, typename SECOND>
class pair {
public:
pair (FIRST const& f, SECOND const& s) : first (f), second (s) {}
FIRST first; // 键
SECOND second; // 值
};
映射的迭代器相当于是指向pair对象的指针。
6)映射中键都是只读的。
7)构建和修改性能较差。适用于结构稳定但是频繁检索的场合。
8)支持"下标"运算,用键做下标,得到对应的值的引用。如果所给出键不存在,会增加一个节点,返回其值,如果键存在,直接返回对应的值。

include <iostream>
#include <map>
using namespace std;
class Candidate {
public:
Candidate (string const& name = "") :
m_name (name), m_votes (0) {}
string const& name (void) const {
return m_name;
}
int votes (void) const {
return m_votes;
}
void vote (void) {
++m_votes;
}
private:
string m_name;
int m_votes;
};
int main (void) {
map<char, Candidate> mcc;
mcc.insert (pair<char, Candidate> (
'A', Candidate ("张飞")));
mcc.insert (make_pair (
'B', Candidate ("赵云")));
mcc['C'] = Candidate ("关羽");
mcc['D'] = Candidate ("马超");
mcc['E'] = Candidate ("黄忠");
typedef map<char, Candidate>::
iterator IT;
/*
pair<IT, bool> res = mcc.insert (
make_pair ('B',
Candidate ("杨健")));
if (! res.second)
cout << "插入失败!" << endl;
*/
mcc['B'] = Candidate ("杨健");
IT it = mcc.begin ();
//    it->first = 'X';
it->second = Candidate ("杨健");
for (int i = 0; i < 10; ++i) {
for (IT it = mcc.begin (); it !=
mcc.end (); ++it)
cout << '(' << it->first
<< ')'
<< it->second.name ()
<< ' ';
cout << endl
<< "请投下宝贵的一票:"
<< flush;
char key;
cin >> key;
IT it = mcc.find (key);
if (it == mcc.end ()) {
cout << "废票!" << endl;
continue;
}
it->second.vote ();
}
IT win = mcc.begin ();
for (IT it = mcc.begin (); it !=
mcc.end (); ++it) {
cout << it->second.name ()
<< "获得"
<< it->second.votes ()
<< "票。" << endl;
if (it->second.votes () >
win->second.votes ())
win = it;
}
cout << "热烈祝贺"
<< win->second.name ()
<< "成功当选首席保洁员!" <<endl;
return 0;
}

 

转载于:https://www.cnblogs.com/LuckCoder/p/8668475.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值