Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4462924
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-09-19 10:40:28



  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <utility>

  5. using std::cout;
  6. using std::string;
  7. using std::map;
  8. using std::endl;
  9. using std::cin;
  10. using std::pair;

  11. int main()
  12. {
  13.     mapword_count;
  14.     //insert a element
  15.     word_count["anna"] = 1;

  16.     cout << word_count["anna"] << endl;
  17.     ++word_count["anna"];
  18.     cout << word_count["anna"] << endl;

  19. //////////////////////////////////////////////////////////////
  20.     //calculation word number
  21. #if 0
  22.     map<string,int> word_count1;
  23.     string word;
  24.     while(cin >> word)
  25.     {
  26.         ++word_count1[word];
  27.         cout << word_count1[word] << endl;
  28.     }
  29. #endif
  30.     
  31.     map<string,int>word_count2;
  32. //    word_count2.insert(map<string,int>::value_type("bnna",1));

  33.     typedef map::value_type valType;
  34.     word_count2.insert(valType("bnna",1));
  35.     
  36. //    word_count2.insert(make_pair("bnna",1));
  37.     cout << word_count2["bnna"] << endl;
  38. //////////////////////////////////////////////////////

  39.     // using count check the key if exists
  40.     int occurs = 0;
  41.     if(word_count2.count("bnna"))//if can find bnna element
  42.     {
  43.         occurs = word_count2["bnna"];
  44.         cout << occurs << endl;
  45.     }
  46.     else
  47.         cout << "cann't find " << endl;
  48.     
  49.     //read elements but do not insert element by using find
  50.     int occurs1 = 0;
  51.     map::iterator it = word_count2.find("bnna");
  52.     if(it != word_count2.end())
  53.         cout << it->second << endl;

  54.     // using erase() delete element
  55.     if(word_count2.erase("bnna"))
  56.         cout << "ok " << " bnna " << " removed\n";
  57.     else
  58.         cout << "oops:" << "bnna" << "not found\n";

  59.     return 0;
  60. }

  1. ywx@ywx:~/desktop/yu$ ./map
  2. 1
  3. 2
  4. 1
  5. 1
  6. 1
  7. ok bnna removed





阅读(1092) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~