std::map提供了两种新增element的方式,一种是c.insert(),和其它container一样,另外一种则是subscripting。
由于std::map会自动sort,所以有『key』的机制,且是const,不能修改,这和Database的观念一样,pk无法修改。在Database中,我们常希望新增一个值时,若不存在就INSERT,若存在就UPDATE,而std::map也有类似的机制,若subscripting不存在则新增,若存在,则传回该key的value(不是UPDATE),由于这种写法,使的程序变的非常精简,下面的程序将统计使用者输入的相同文字的个数:
1

/**/
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : MapAddElementBySubscripting.cpp
5
Compiler : Visual C++ 8.0
6
Description : Demo how to add Map element by subscrpting
7
Release : 11/16/2006
8
*/
9
10
#include
<
iostream
>
11
#include
<
map
>
12
#include
<
string
>
13
14
int
main()
{
15
std::map<std::string, int> wordCount;
16
// Only one line to caculate word count
17
for(std::string word; std::cin >> word; ++wordCount[word]);
18
19
// cout the result
20
for(std::map<std::string, int>::iterator iter = wordCount.begin();
21
iter != wordCount.end(); ++iter)
{
22
std::cout << iter->first << " " << iter->second << std::endl;
23
}
24
}


2

3

4

5

6

7

8

9

10

11

12

13

14



15

16

17

18

19

20

21



22

23

24

关键在于第17行,仅用一行的程序就做到了相同字数统计,为什么呢?当使用者每输入一个字时,若未在wordCount这个map,则insert之,由于int为built-in type,所以initialize为0,最后再++成为1,若所输入的字已经在wordCount这个map,则传回该key目前的value,必且++后存回此map,因此才能一行达到统计的功能。