(原創) 如何使用subscripting的方式新增std::map? (C/C++) (STL)

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
 4Filename    : MapAddElementBySubscripting.cpp
 5Compiler    : Visual C++ 8.0
 6Description : Demo how to add Map element by subscrpting
 7Release     : 11/16/2006
 8*/

 9
10#include <iostream>
11#include <map>
12#include <string>
13
14int main() {
15  std::map<std::stringint> 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::stringint>::iterator iter = wordCount.begin();
21    iter != wordCount.end(); ++iter) {
22      std::cout << iter->first << " " << iter->second << std::endl;
23  }

24}

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

posted on 2006-11-16 01:00  真 OO无双  阅读(923)  评论(0编辑  收藏  举报

导航