zoukankan      html  css  js  c++  java
  • C++ 字典 map详解

    C++ 字典 map详解

    2019-01-18 23:32:08 lh_lyh 阅读数 1123更多

    文章目录


    容器重要属性

    • 通过键值访问,而不是位置
    • 按Key有序排列
    • 键与值一 一对应
    • 键唯一,不存在相同的键对应不同的值

    操作

    • 迭代器

      1. begin 指向起始

      2. end 指向末尾

      3. rbegin 指向倒序起始(即末尾)

      4. rend 指向倒序末尾(即起始)

      // map::begin/end
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> mymap;
      
        mymap['b'] = 100;
        mymap['a'] = 200;
        mymap['c'] = 300;
      
        // show content:
        for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
          std::cout << it->first << " => " << it->second << '\n';
      
        return 0;
      }
      // Output:
      //	a => 200
      //	b => 100
      //	c => 300
      
    • 大小

      1. empty 判断容器是否为空

      // map::empty
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> mymap;
      
        mymap['a']=10;
        mymap['b']=20;
        mymap['c']=30;
      
        while (!mymap.empty())
        {
          std::cout << mymap.begin()->first << " => " << mymap.begin()->second << '\n';
          mymap.erase(mymap.begin());
        }
      
        return 0;
      }
      
      //Output:
      //a => 10
      //b => 20
      //c => 30
      

      2. size 返回容器大小

      // map::size
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> mymap;
        mymap['a']=101;
        mymap['b']=202;
        mymap['c']=302;
      
        std::cout << "mymap.size() is " << mymap.size() << '\n';
      
        return 0;
      }
      //Output:
      //mymap.size() is 3
      

      3. max_size 返回容器最大尺寸

    • 元素访问

      1. operater[ ]

      2. at

      // accessing mapped values: at / operator[]
      #include <iostream>
      #include <string>
      #include <map>
      
      int main ()
      {
       std::map<std::string,int> mymap = {
                     { "alpha", 0 },
                     { "beta", 0 },
                     { "gamma", 0 } };
      
       mymap.at("alpha") = 10;
       mymap["beta"] = 20;
       mymap.at("gamma") = 30;
      
       for (auto& x: mymap) {
         std::cout << x.first << ": " << x.second << '\n';
       }
      
       return 0;
      }
      //Output:
      //alpha: 10
      //beta: 20
      //gamma: 30
      
    • 修改元素

      1. insert 插入元素

      方法一:直接插入键值对mymap.insert ( std::pair<char,int>('a',100) );
      方法二:通过迭代器指定位置并插入std::map<char,int>::iterator it = mymap.begin(); mymap.insert (it, std::pair<char,int>('b',300)); // max efficiency inserting
      方法三:通过迭代器范围插入,区间半包含([ , ))
      std::map<char,int> anothermap; anothermap.insert(mymap.begin(),mymap.find('c'));

      // map::insert (C++98)
      #include <iostream>
      #include <map>
      
      int main ()
      {
       std::map<char,int> mymap;
      
       // first insert function version (single parameter):
       mymap.insert ( std::pair<char,int>('a',100) );
       mymap.insert ( std::pair<char,int>('z',200) );
      
       std::pair<std::map<char,int>::iterator,bool> ret;
       ret = mymap.insert ( std::pair<char,int>('z',500) );
       if (ret.second==false) {
         std::cout << "element 'z' already existed";
         std::cout << " with a value of " << ret.first->second << '\n';
       }
      
       // second insert function version (with hint position):
       std::map<char,int>::iterator it = mymap.begin();
       mymap.insert (it, std::pair<char,int>('b',300));  // max efficiency inserting
       mymap.insert (it, std::pair<char,int>('c',400));  // no max efficiency inserting
      
       // third insert function version (range insertion):
       std::map<char,int> anothermap;
       anothermap.insert(mymap.begin(),mymap.find('c'));
      
       // showing contents:
       std::cout << "mymap contains:\n";
       for (it=mymap.begin(); it!=mymap.end(); ++it)
         std::cout << it->first << " => " << it->second << '\n';
      
       std::cout << "anothermap contains:\n";
       for (it=anothermap.begin(); it!=anothermap.end(); ++it)
         std::cout << it->first << " => " << it->second << '\n';
      
       return 0;
      }
      //Output:
      //element 'z' already existed with a value of 200
      //mymap contains:
      //a => 100
      //b => 300
      //c => 400
      //z => 200
      //anothermap contains:
      //a => 100
      //b => 300
      

      2. erase 删除元素

      // erasing from map
      #include <iostream>
      #include <map>
      
      int main ()
      {
       std::map<char,int> mymap;
       std::map<char,int>::iterator it;
      
       // insert some values:
       mymap['a']=10;
       mymap['b']=20;
       mymap['c']=30;
       mymap['d']=40;
       mymap['e']=50;
       mymap['f']=60;
      
       it=mymap.find('b');
       mymap.erase (it);                   // erasing by iterator
      
       mymap.erase ('c');                  // erasing by key
      
       it=mymap.find ('e');
       mymap.erase ( it, mymap.end() );    // erasing by range
      
       // show content:
       for (it=mymap.begin(); it!=mymap.end(); ++it)
         std::cout << it->first << " => " << it->second << '\n';
      
       return 0;
      }
      //Output:
      //a => 10
      //d => 40
      

      3. swap 交换两个map容器内容

      // swap maps
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> foo,bar;
      
        foo['x']=100;
        foo['y']=200;
      
        bar['a']=11;
        bar['b']=22;
        bar['c']=33;
      
        foo.swap(bar);
      
        std::cout << "foo contains:\n";
        for (std::map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it)
          std::cout << it->first << " => " << it->second << '\n';
      
        std::cout << "bar contains:\n";
        for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
          std::cout << it->first << " => " << it->second << '\n';
      
        return 0;
      }
      //Output:
      //foo contains:
      //a => 11
      //b => 22
      //c => 33
      //bar contains:
      //x => 100
      //y => 200
      

      4. clear 清除容器

      5. emplace 构造并插入元素

      // map::emplace
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> mymap;
      
        mymap.emplace('x',100);
        mymap.emplace('y',200);
        mymap.emplace('z',100);
      
        std::cout << "mymap contains:";
        for (auto& x: mymap)
          std::cout << " [" << x.first << ':' << x.second << ']';
        std::cout << '\n';
      
        return 0;
      }
      //Output:
      //mymap contains: [x:100] [y:200] [z:100]
      
    • 操作

      1. 赋值

      // assignment operator with maps
      #include <iostream>
      #include <map>
      
      int main ()
      {
       std::map<char,int> first;
       std::map<char,int> second;
      
       first['x']=8;
       first['y']=16;
       first['z']=32;
      
       second=first;                // second now contains 3 ints
       first=std::map<char,int>();  // and first is now empty
      
       std::cout << "Size of first: " << first.size() << '\n';
       std::cout << "Size of second: " << second.size() << '\n';
       return 0;
      }
      //Output:
      //Size of first: 0
      //Size of second: 3
      

      2. find 获得指向元素的迭代器

      // map::find
      #include <iostream>
      #include <map>
      
      int main ()
      {
       std::map<char,int> mymap;
       std::map<char,int>::iterator it;
      
       mymap['a']=50;
       mymap['b']=100;
       mymap['c']=150;
       mymap['d']=200;
      
       it = mymap.find('b');
       if (it != mymap.end())
         mymap.erase (it);
      
       // print content:
       std::cout << "elements in mymap:" << '\n';
       std::cout << "a => " << mymap.find('a')->second << '\n';
       std::cout << "c => " << mymap.find('c')->second << '\n';
       std::cout << "d => " << mymap.find('d')->second << '\n';
      
       return 0;
      }
      //Output:
      //elements in mymap:
      //a => 50
      //c => 150
      //d => 200
      

      3. count 对某个键的元素计数

      // map::count
      #include <iostream>
      #include <map>
      
      int main ()
      {
        std::map<char,int> mymap;
        char c;
      
        mymap ['a']=101;
        mymap ['c']=202;
        mymap ['f']=303;
      
        for (c='a'; c<'h'; c++)
        {
          std::cout << c;
          if (mymap.count(c)>0)
            std::cout << " is an element of mymap.\n";
          else 
            std::cout << " is not an element of mymap.\n";
        }
      
        return 0;
      }
      //Output:
      //a is an element of mymap.
      //b is not an element of mymap.
      //c is an element of mymap.
      //d is not an element of mymap.
      //e is not an element of mymap.
      //f is an element of mymap.
      //g is not an element of mymap.
      

      4. lower_bound 返回下边界的迭代器

      返回指向该元素的迭代器

      5. upper_bound 返回上边界的迭代器

      返回指向该元素的下一个元素的迭代器

      // map::lower_bound/upper_bound
      #include <iostream>
      #include <map>
      
      int main ()
      {
       std::map<char,int> mymap;
       std::map<char,int>::iterator itlow,itup;
      
       mymap['a']=20;
       mymap['b']=40;
       mymap['c']=60;
       mymap['d']=80;
       mymap['e']=100;
      
       itlow=mymap.lower_bound ('b');  // itlow points to b
       itup=mymap.upper_bound ('d');   // itup points to e (not d!)
      
       mymap.erase(itlow,itup);        // erases [itlow,itup)
      
       // print content:
       for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
         std::cout << it->first << " => " << it->second << '\n';
      
       return 0;
      }
      //Output:
      //a => 20
      //e => 100
      

      6. equal_range 获得相同元素的范围

  • 相关阅读:
    LeetCode 32. 最长有效括号(Longest Valid Parentheses)
    LeetCode 141. 环形链表(Linked List Cycle)
    LeetCode 160. 相交链表(Intersection of Two Linked Lists)
    LeetCode 112. 路径总和(Path Sum)
    LeetCode 124. 二叉树中的最大路径和(Binary Tree Maximum Path Sum)
    LightGBM新特性总结
    sql service 事务与锁
    C#泛型实例详解
    C# 中的委托和事件(详解)
    C# DateTime日期格式化
  • 原文地址:https://www.cnblogs.com/grj001/p/12223496.html
Copyright © 2011-2022 走看看