c++ map 使用方法

c++ map 使用方法:


  • map是存储排序的键值对的关联容器,其中每个键都是唯一的,可以插入或删除,但不能更改。但是与键关联的值可以更改。

  • 参数

      1. key: 存储在map中的键的数据类型
      1. type: 存储在map中的值的数据类型
      1. compare:一个比较类,它接受两个bool类型相同的参数,并返回一个值. less <“ key”>是默认值
      1. alloc:分配器对象的类型
  • 创建map

      1. 使用数组索引符号进行赋值:
          using namespace std;
          map Employees;
          Employees[101] = "John";
          Employees[102] = "Nikita";
          cout << Employees.size();
          for (map::iterator i = Employees.begin(); i != Employees.end(); i++) {
              cout << (*i).first << ":" << (*i).second << endl; // beign points to the 
                                                                // first element in the map
                                                                // end points to the next element of the last element!
          }
          for (map::iterator i = Employees.rbegin(); i != Employees.rend(); i++) {
              cout << (*i).first << ":" << (*i).second << endl; // rbeign points to the 
                                                                // last element in the map
                                                                // end points to the previous element of the first element!
          }
      
  • 成员函数:

      1. 构造/析构函数:constructor, destructor, operator=
          operator=()
          // 1. 将一个map的内容复制到另一个map
          using namespace std;
      
          int main(void) {
      
              map<char, int> m1 = {
                          {'a', 10},
                          {'b', 20},
                          {'c', 30} };
      
              cout << "Map m1包含以下元素" << endl;
              for (auto it = m1.begin(); it != m1.end(); ++it)
              cout << it->first << " = " << it->second << endl;
              
              map<char, int> m2 = m1;  
              cout<<"\n将元素从m1复制到m2之后... \n";  
              
              cout << "\nMap m2包含以下元素" << endl;
              for (auto it = m2.begin(); it != m2.end(); ++it)
              cout << it->first << " = " << it->second << endl;
      
              return 0;
          }
      Map m1包含以下元素
      a = 10
      b = 20
      c = 30
      
      将元素从m1复制到m2之后...
      
      Map m2包含以下元素
      a = 10
      b = 20
      c = 30
      
          // 2. 将一个map的元素移动到另一个
          using namespace std;
      
          int main(void) {
          
          map<char, int> m1 = {
                      {'a', 1},
                      {'b', 2},
                      {'c', 3} };
      
      
              cout << "Map m1包含以下元素" << endl;
              for (auto it = m1.begin(); it != m1.end(); ++it)
              cout << it->first << " = " << it->second << endl;
              
              map<char, int> m2 = move(m1); 
              cout<<"\n将元素从m1移到m2后... \n";  
              
              cout << "\nMap m2包含以下元素" << endl;
              for (auto it = m2.begin(); it != m2.end(); ++it)
              cout << it->first << " = " << it->second << endl;
      
              cout << m1.size();
              cout << m2.size();
      
          return 0;
          }
      Map m1包含以下元素
      a = 1
      b = 2
      c = 3
      
      将元素从m1移到m2后...
      
      Map m2包含以下元素
      a = 1
      b = 2
      c = 3
      
      m1 size = 0;
      m2 size = 3;
      
      1. 迭代器
      | function | description                          |
      | -------- | ------------------------------------ |
      | begin    | 返回指向map中第一个元素的迭代器      |
      | cbegin   | 返回指向map中第一个元素的const迭代器 |
      | end      | 返回指向末尾的迭代器                 |
      | cend     | 返回指向末尾的常量迭代器             |
      | rbegin   | 返回指向末尾的反向迭代器             |
      | rend     | 返回指向起点的反向迭代器             |
      
          // When you declare an iterator as constant using cbegin, you are essentially telling the compiler 
          // that you will not modify the elements in the container through that iterator.
              int main() {
                  std::vector<int> v = {1, 2, 3, 4, 5};
      
                  // using begin to modify the first element
                  *v.begin() = 10;
                  std::cout << "v[0] after using begin(): " << v[0] << std::endl;
      
                  // using cbegin to try to modify the first element
                  *v.cbegin() = 20;  // This will give a compiler error!
                  std::cout << "v[0] after using cbegin(): " << v[0] << std::endl;
      
                  return 0;
              }
      
      1. 容量
      | function | description             |
      | -------- | ----------------------- |
      | empty    | 如果map为空,则返回true |
      | size     | 返回map中的元素数       |
      | max_size | 返回map的最大容量       |
      
      1. 元素访问
          1. operator[]: map['key'] = new value; or cout << map['key];
          2. at: map.at(key) = value; or cout << map.at(key);
      
      1. 修饰符
      | function | description                 |
      | -------- | --------------------------- |
      | insert   | 在map中插入元素             |
      | erase    | 从map中删除元素             |
      | swap     | 交换map内容                 |
      | clear    | 删除map所有元素             |
      | emplace  | 构造新元素并将其插入到map中 |
      
      // 将元素插入map,默认插入到最后
          using namespace std;
      
          int main() {
          map<char, int> m = {
                      {'a', 1},
                      {'b', 2},
                      {'c', 3},
                      };
      
          //插入新元素
          m.insert(pair<char, int>('d', 4));
          m.insert(pair<char, int>('e', 5));
          m.insert(m.begin(), pair<char, int>('f', 0));
      
          cout << "Map包含以下元素" << endl;
      
          for (auto it = m.begin(); it != m.end(); ++it)
              cout << it->first << " = " << it->second << endl;
      
          return 0;
          }
      Map包含以下元素
      f = 0
      a = 1
      b = 2
      c = 3
      d = 4
      e = 5
      
      // 将一个map的元素插入另一个map(insert()函数用于从m1的开头到m1的结尾插入m1到m2的元素)
          using namespace std;
      
          int main() {
          
          map<char, int> m1 = {
                      {'a', 1},
                      {'b', 2},
                      {'c', 3},
                      {'d', 4},
                      {'e', 5},
                      };
      
          map<char, int> m2;  // 创建新的map容器 m2
          m2.insert(m1.begin(),m1.end());   //从头到尾插入m1到m2的元素
      
          cout << "Map包含以下元素" << endl;
      
          for (auto it = m2.begin(); it != m2.end(); ++it){
              cout << it->first << " = " << it->second << endl;
          }     
          return 0;
          }
      Map包含以下元素
      a = 1
      b = 2
      c = 3
      d = 4
      e = 5
      
      
      // 以给定的键值擦除map的元素
          using namespace std;
          int main ()
          {
          map<char,int> mymap;
          map<char,int>::iterator it;
      
          mymap['a']=10;
          mymap['b']=20;
          mymap['c']=30;
          mymap['d']=40;
          
          cout<<"删除元素之前: \n";
          for (it=mymap.begin(); it!=mymap.end(); ++it)
              std::cout << it->first << " => " << it->second << '\n';
      
          mymap.erase ('c');               // erasing by key
      
          it=mymap.find('b');
          mymap.erase (it);                // erasing by iterator
      
          mymap.erase ( mymap.begin () ,  mymap.end () );   // erasing by range
      
          cout<<"\n删除元素后: \n";
          for (it=mymap.begin(); it!=mymap.end(); ++it)
              std::cout << it->first << " => " << it->second << '\n';
          return 0;
          }
      删除元素之前: 
      a => 10
      b => 20
      c => 30
      d => 40
      
      删除元素后: 
      a => 10
      d => 40
      
      // 将一个map的元素交换到另一个, 并删除map中所有元素
      
          using namespace std;
      
          int main(void) {
          map<char, int> m1 = {
              {'a', 1},
              {'b', 2},
              {'c', 3},
              {'d', 4},
              {'e', 5},
              };
      
          map<char, int> m2;
      
          m2.swap(m1);
      
          cout << "Map包含以下元素" << endl;
      
          for (auto it = m2.begin(); it != m2.end(); ++it)
              cout << it->first << " = " << it->second << endl;
          
          m2.clear();
          cout << m2.size();
      
          return 0;
          }
      Map包含以下元素
      a = 1
      b = 2
      c = 3
      d = 4
      e = 5
      m2 size = 0
      
      // emplace()函数,通过在容器中插入新元素来扩展map容器。元素是直接构建的(既不复制也不移动)
      // 返回一个布尔对,它表示是否发生插入,并返回一个指向新插入元素的迭代器
      
          using namespace std;
      
          #include <map>
          int main()
          {
              map<string, string> m;
          
              //使用pair的move构造函数
              m.emplace(make_pair(string("a"), string("a")));
          
              //使用对的转换move构造函数
              m.emplace(make_pair("b", "abcd"));
          
              //使用pair的模板构造函数
              m.emplace("d", "ddd");
          
              //使用pair的分段构造函数
              m.emplace(piecewise_construct,
                      forward_as_tuple("c"),
                      forward_as_tuple(10, 'c'));
          
              for (const auto &p : m) {
                  cout << p.first << " => " << p.second << '\n';
              }
          }
      a => a
      b => abcd
      c => cccccccccc
      d => ddd
      
      1. 操作方式
      | function    | description              |
      | ----------- | ------------------------ |
      | find        | 搜索具有给定键的元素     |
      | count       | 获取与给定键匹配的元素数 |
      | lower_bound | 返回迭代器的下限         |
      | upper_bound | 返回一个迭代器到上限     |
      // find: 查找具有给定键值的元素
          using namespace std;
          int main(void) {
          map<char, int> m = {
                      {'a', 100},
                      {'b', 200},
                      {'c', 300},
                      {'d', 400},
                      {'e', 500},
                      };
      
          auto it = m.find('c');
      
          cout << "迭代器指向 " << it->first << 
              " = " << it->second << endl;
      
          return 0;
          }
      迭代器指向 c = 300
      // count: If a key exists in the map, count() returns the number of times the key appears in the map 0 or 1
          int main() {
          std::map<std::string, int> my_map;
      
          // Insert some values into the map
          my_map.insert({"apple", 3});
          my_map.insert({"banana", 2});
          my_map.insert({"orange", 5});
          my_map.insert({"grape", 1});
      
          // Check if a key exists in the map using count()
          if (my_map.count("banana") > 0) {
              std::cout << "The key 'banana' exists in the map!" << std::endl;
          }
          else {
              std::cout << "The key 'banana' does not exist in the map." << std::endl;
          }
      
          // Check if a key does not exist in the map using count()
          if (my_map.count("watermelon") > 0) {
              std::cout << "The key 'watermelon' exists in the map!" << std::endl;
          }
          else {
              std::cout << "The key 'watermelon' does not exist in the map." << std::endl;
          }
      
          return 0;
          }
      The key 'banana' exists in the map!
      The key 'watermelon' does not exist in the map.
      
      1. 非成员重载函数
      the operator is used to compare two std::map objects!
      1. When comparing two maps, the operator first compares the sizes of the two maps. If the sizes are different, the map with the smaller size is considered "less" than the other map.
      2. If the sizes of the two maps are the same, the operator compares the keys of the maps one by one in a lexicographic order. That is, it compares the first key of each map; if they are equal, it compares the second key of each map, and so on, until it finds a pair of keys that are different. The map with the smaller key at the first differing position is considered "less" than the other map
      | function | description                        |
      | -------- | ---------------------------------- |
      | ==       | 检查两个map是否相等                |
      | <        | 检查第一个map是否小于其他map       |
      | <=       | 检查第一个map是否小于或等于其他map |
      | >        | 检查第一个map是否大于其他map       |
      | >=       | 检查第一个map是否大于或等于其他map |
      
          #include <iostream>
          #include <map>
      
          int main() {
              std::map<int, char> map1 = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
              std::map<int, char> map2 = {{1, 'a'}, {2, 'b'}, {3, 'd'}};
              std::map<int, char> map3 = {{1, 'a'}, {2, 'b'}};
              std::map<int, char> map4 = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
      
              std::cout << std::boolalpha;  // Print boolean values as "true" or "false"
              std::cout << "map1 < map2: " << (map1 < map2) << std::endl;  // true
              std::cout << "map1 < map3: " << (map1 < map3) << std::endl;  // false
              std::cout << "map1 < map4: " << (map1 < map4) << std::endl;  // false
      
              return 0;
          }
      map1 < map2: true
      // map1 and map2 have the same keys and values up to the third element, 
      // where map2 has a different value for the key 3. Therefore, map1 is 
      // considered "less" than map2"
      map1 < map3: false
      map1 < map4: false
      
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值