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; }