STL Map

本文深入探讨了C++ Map容器的使用方法,包括基本构造、数据添加、查找、删除、交换、排序等问题,提供了实用的操作技巧。

STL中的vector、list的应用及用法都很熟习,但在Map的应用上一直有些迷糊,花了点时间研究了一下应用。

Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!

注意:在map<key,value>类型中对key的要求:
因为map内部的实现采用的是一颗红黑树(类似平衡二叉树),所以,它要按照key值比较大小(弱排序),所以,对key类型的唯一要求是,它必须支持<操作,至于是否支持其他的关系或相等元算,不做要求。例如::  我们定义了一个类作为Key,那么必须让它支持<操作,否则是不可以的。

1. map最基本的构造函数;
   map<string , int >mapstring;         map<int ,string >mapint;
   map<sring, char>mapstring;         map< char ,string>mapchar;
   map<char ,int>mapchar;            map<int ,char >mapint;
2. map添加数据;
   map<int ,string> maplive;  
   1.maplive.insert(pair<int,string>(102,"aclive"));
   2.maplive.insert(map<int,string>::value_type(321,"hai"));
   3, maplive[112]="April";//map中最简单最常用的插入添加!
3,map中元素的查找:
   find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。        
   map<int ,string >::iterator l_it;; 
   l_it=maplive.find(112);
   if(l_it==maplive.end())
                cout<<"we do not find 112"<<endl;
   else cout<<"wo find 112"<<endl;
4,map中元素的删除:
   如果删除112;
   map<int ,string >::iterator l_it;;
   l_it=maplive.find(112);
   if(l_it==maplive.end())
        cout<<"we do not find 112"<<endl;
   else  maplive.erase(l_it);  //delete 112;
5,map中 swap的用法:
  Map中的swap不是一个容器中的元素交换,而是两个容器交换;
  For example:
  #include <map>
  #include <iostream>
  using namespace std;
  int main( )
  {
      map <int, int> m1, m2, m3;
      map <int, int>::iterator m1_Iter;
      m1.insert ( pair <int, int>  ( 1, 10 ) );
      m1.insert ( pair <int, int>  ( 2, 20 ) );
      m1.insert ( pair <int, int>  ( 3, 30 ) );
      m2.insert ( pair <int, int>  ( 10, 100 ) );
      m2.insert ( pair <int, int>  ( 20, 200 ) );
      m3.insert ( pair <int, int>  ( 30, 300 ) );
   cout << "The original map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter->second;
      cout   << "." << endl;
   // This is the member function version of swap
   //m2 is said to be the argument map; m1 the target map
   m1.swap( m2 );
   cout << "After swapping with m2, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout  << "." << endl;
   cout << "After swapping with m2, map m2 is:";
   for ( m1_Iter = m2.begin( ); m1_Iter != m2.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout  << "." << endl;
   // This is the specialized template version of swap
   swap( m1, m3 );
   cout << "After swapping with m3, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout   << "." << endl;
}
6.map的sort问题:
  Map中的元素是自动按key升序排序,所以不能对map用sort函数:
  For example:
  #include <map>
  #include <iostream>
  using namespace std;
 int main( )
 {
   map <int, int> m1;
   map <int, int>::iterator m1_Iter;
   m1.insert ( pair <int, int>  ( 1, 20 ) );
   m1.insert ( pair <int, int>  ( 4, 40 ) );
   m1.insert ( pair <int, int>  ( 3, 60 ) );
   m1.insert ( pair <int, int>  ( 2, 50 ) );
   m1.insert ( pair <int, int>  ( 6, 40 ) );
   m1.insert ( pair <int, int>  ( 7, 30 ) );
   cout << "The original map m1 is:"<<endl;
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout <<  m1_Iter->first<<" "<<m1_Iter->second<<endl;
  
}
  The original map m1 is:
  1 20
  2 50
  3 60
  4 40
  6 40
  7 30
  请按任意键继续. . .
7,   map的基本操作函数:
      C++ Maps是一种关联式容器,包含“关键字/值”对
      begin()          返回指向map头部的迭代器
      clear()         删除所有元素
      count()          返回指定元素出现的次数
      empty()          如果map为空则返回true
      end()            返回指向map末尾的迭代器
      equal_range()    返回特殊条目的迭代器对
      erase()          删除一个元素
      find()           查找一个元素
      get_allocator()  返回map的配置器
      insert()         插入元素
      key_comp()       返回比较元素key的函数
      lower_bound()    返回键值>=给定元素的第一个位置
      max_size()       返回可以容纳的最大元素个数
      rbegin()         返回一个指向map尾部的逆向迭代器
      rend()           返回一个指向map头部的逆向迭代器
      size()           返回map中元素的个数
      swap()            交换两个map
      upper_bound()     返回键值>给定元素的第一个位置
      value_comp()      返回比较元素value的函数
                                                     
<think>好的,我现在需要回答用户关于C++ STLmap的用法和相关示例的问题。首先,用户提到了引用[1]和[2],其中引用[1]讨论了泛型算法和自定义比较函数的重要性,引用[2]提到了map的find()方法。用户可能想了解map的基本用法、常见操作以及实际示例。 首先,我应该从map的基本概念开始。map是关联容器,存储键值对,按键排序。需要解释它的模板参数,比如键类型、值类型、比较函数和分配器。然后,常用的成员函数,比如插入、访问元素、查找、删除和遍历。 插入元素可以使用insert()或者operator[]。需要注意的是,当使用operator[]时,如果键不存在,会创建一个新条目,而insert()则不会覆盖已存在的键。这点需要说明清楚。 访问元素方面,operator[]和at()的区别在于,at()在键不存在时会抛出异常,而operator[]会创建。这点需要强调,避免用户在使用时出现未预期的行为。 查找元素主要用find()方法,返回迭代器。如果找不到,返回end()。需要提醒用户检查返回值,避免解引用无效迭代器。 删除元素有erase(),可以通过键或迭代器删除。遍历时通常使用迭代器或者C++11的范围for循环,这时候需要提到如何获取键和值。 接下来是示例代码。应该包括创建map、插入元素、访问、查找、删除和遍历的操作。代码要简洁,注释明确。例如,使用insert插入多个键值对,使用operator[]添加新元素,使用find检查是否存在某个键,并用erase删除元素。 然后,根据用户提供的引用,特别是引用[1],可以提到自定义比较函数。比如,默认是less,但用户可以自定义排序规则,比如按降序排列。给出一个示例,使用greater作为比较函数,并展示如何声明这样的map。 另外,性能方面,map基于红黑树,操作时间复杂度是O(log n),这点需要提及,让用户了解其效率特点。 在生成相关问题的时候,需要考虑用户可能进一步的问题,比如map与unordered_map的区别,如何处理自定义类型作为键,性能优化,插入重复键的处理,以及实际应用场景。这些问题可以帮助用户深入理解map的使用和选择合适的数据结构。 最后,确保所有代码示例符合C++语法,并且解释清晰,避免术语混淆。同时,引用用户提供的参考资料,特别是在提到自定义比较函数时引用[1],以及在讨论find()方法时引用[2]。</think>### C++ STL map 用法详解 `std::map` 是 C++ STL 中的关联容器,以键值对(key-value)形式存储数据,并按键自动排序。以下是其核心用法和示例: --- #### 1. 基本定义与初始化 ```cpp #include <map> #include <string> // 定义键为int,值为string的map,默认按升序排列 std::map<int, std::string> student_map; // 初始化示例 std::map<std::string, int> age_map = { {"Alice", 25}, {"Bob", 30} }; ``` --- #### 2. 插入元素 - **`insert()` 方法** 插入新键值对,若键已存在则不会覆盖: ```cpp student_map.insert(std::make_pair(101, "Tom")); student_map.insert({102, "Jerry"}); // C++11 简化语法 ``` - **`operator[]`** 直接通过键赋值,若键不存在则创建新条目: ```cpp age_map["Charlie"] = 28; // 新增键 age_map["Alice"] = 26; // 覆盖原有值 ``` --- #### 3. 访问元素 - **`operator[]` 与 `at()`** ```cpp std::cout << age_map["Bob"]; // 输出30(若键不存在会创建默认值) std::cout << age_map.at("Bob"); // 输出30(若键不存在抛出std::out_of_range异常) ``` --- #### 4. 查找元素 - **`find()` 方法** 返回指向键的迭代器,若未找到则返回`end()` [^2]: ```cpp auto it = age_map.find("Alice"); if (it != age_map.end()) { std::cout << "Found: " << it->second; // 输出值 } ``` --- #### 5. 删除元素 - **`erase()` 方法** 通过键或迭代器删除: ```cpp age_map.erase("Bob"); // 删除键为"Bob"的条目 auto it = age_map.find("Alice"); if (it != age_map.end()) { age_map.erase(it); // 通过迭代器删除 } ``` --- #### 6. 遍历元素 ```cpp // 使用迭代器遍历 for (auto it = age_map.begin(); it != age_map.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } // C++11 范围for循环 for (const auto& pair : age_map) { std::cout << pair.first << ": " << pair.second << std::endl; } ``` --- #### 7. 自定义排序规则 可通过模板参数指定比较函数(如降序排列)[^1]: ```cpp #include <functional> std::map<int, std::string, std::greater<int>> desc_map; desc_map[3] = "Third"; desc_map[1] = "First"; // 遍历顺序为3→1 ``` --- #### 8. 性能特点 - **时间复杂度** 插入、删除、查找均为 $O(\log n)$,基于红黑树实现。 - **适用场景** 需要按键有序访问或频繁查找/更新的场景。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值