std::map 是 C++ 标准库中的一个关联容器,它存储的是键值对(key - value pairs),并且按照键(key)的顺序进行排序。下面为你详细介绍 std::map 的使用方法,包含代码示例与注释。在 C++ 里,std::map 是标准模板库(STL)中的一个关联容器,它能将键(key)和值(value)一一对应起来。每个键都是唯一的,通过键可以快速查找、插入、删除对应的值。下面为你详细介绍 std::map 的使用,包含概念解释、代码示例及注释。

1. 包含头文件

要使用 std::map,需要包含 <map> 头文件。

#include <map>

2. 定义 std::map

定义 std::map 时,需要指定键(key)和值(value)的数据类型。以下是一个简单的定义示例:

#include <iostream>
#include <map>
#include <string>

int main() {
    // 定义一个 std::map,键为 std::string 类型,值为 int 类型
    std::map<std::string, int> myMap;
    return 0;
}

3. 插入元素

可以使用 insert 方法或者 [] 运算符向 std::map 中插入元素。

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> myMap;

    // 使用 insert 方法插入元素
    myMap.insert(std::pair<std::string, int>("apple", 10));

    // 也可以使用 make_pair 函数
    myMap.insert(std::make_pair("banana", 20));

    // 使用 [] 运算符插入元素
    myMap["cherry"] = 30;

    return 0;
}

4. 访问元素

可以使用 [] 运算符或者 at() 方法访问 std::map 中的元素。

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> myMap;
    myMap["apple"] = 10;
    myMap["banana"] = 20;
    myMap["cherry"] = 30;

    // 使用 [] 运算符访问元素
    std::cout << "Value of apple: " << myMap["apple"] << std::endl;

    // 使用 at() 方法访问元素
    try {
        std::cout << "Value of banana: " << myMap.at("banana") << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Element not found: " << e.what() << std::endl;
    }

    return 0;
}

5. 遍历元素

可以使用迭代器(iterator)来遍历 std::map 中的元素。

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> myMap;
    myMap["apple"] = 10;
    myMap["banana"] = 20;
    myMap["cherry"] = 30;

    // 使用迭代器遍历元素
    for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    // C++11 及以上版本可以使用范围 for 循环
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

6. 删除元素

可以使用 erase 方法删除 std::map 中的元素。

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> myMap;
    myMap["apple"] = 10;
    myMap["banana"] = 20;
    myMap["cherry"] = 30;

    // 删除指定键的元素
    myMap.erase("banana");

    // 遍历元素验证删除结果
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

7. 检查元素是否存在

可以使用 find() 方法检查某个键是否存在于 std::map 中。

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> myMap;
    myMap["apple"] = 10;
    myMap["banana"] = 20;
    myMap["cherry"] = 30;

    // 检查键是否存在
    std::map<std::string, int>::iterator it = myMap.find("banana");
    if (it != myMap.end()) {
        std::cout << "Key 'banana' exists, value: " << it->second << std::endl;
    } else {
        std::cout << "Key 'banana' does not exist." << std::endl;
    }

    return 0;
}

完整代码示例

下面是一个包含上述所有操作的完整代码示例:

#include <iostream>
#include <map>
#include <string>

int main() {
    // 定义一个 std::map,键为 std::string 类型,值为 int 类型
    std::map<std::string, int> myMap;

    // 插入元素
    myMap.insert(std::pair<std::string, int>("apple", 10));
    myMap.insert(std::make_pair("banana", 20));
    myMap["cherry"] = 30;

    // 访问元素
    std::cout << "Value of apple: " << myMap["apple"] << std::endl;
    try {
        std::cout << "Value of banana: " << myMap.at("banana") << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Element not found: " << e.what() << std::endl;
    }

    // 遍历元素
    std::cout << "Elements in the map:" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // 删除元素
    myMap.erase("banana");
    std::cout << "Elements in the map after erasing 'banana':" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // 检查元素是否存在
    std::map<std::string, int>::iterator it = myMap.find("banana");
    if (it != myMap.end()) {
        std::cout << "Key 'banana' exists, value: " << it->second << std::endl;
    } else {
        std::cout << "Key 'banana' does not exist." << std::endl;
    }

    return 0;
}    

这个示例代码展示了 std::map 的基本使用方法,包括定义、插入、访问、遍历、删除和检查元素是否存在等操作。你可以将上述代码保存为 .cpp 文件,然后使用 C++ 编译器进行编译和运行。

6 条评论

  • @ 2025-5-5 19:19:05
    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    int main() {
    	map<string, int> myMap;
    	
    	// 使用 insert 方法插入元素
    	//myMap.insert(std::pair<std::string, int>("apple", 10));
    	
    	// 也可以使用 make_pair 函数
    	//myMap.insert(std::make_pair("banana", 20));
    	
    	// 使用 [] 运算符插入元素
    	myMap["cherry"] = 30;
    	myMap["cherry"] = 50;
    	myMap["apple"] = 1;
    	myMap["ban"] = 2;
    	//cout<<myMap["ban"]<<endl;
    	// C++11 及以上版本可以使用范围 for 循环
    	for (auto pair : myMap) {//auto 是自适应匹配类型
    		cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
    	}
    	return 0;
    }
    
    
    • @ 2025-5-1 20:02:25

      📚 一、map 是什么?

      在C++中,map 是一个 关联容器(associative container),属于 STL(标准模板库) 的一部分。

      它用来存储 键值对(key-value pair),每个键是唯一的,且会自动按照键的顺序进行排序。

      特点:

      • 存储的是 键值对(pair)
      • 键(key)唯一
      • 自动按键排序(默认升序)
      • 支持高效的查找、插入和删除操作

      🧰 二、如何使用 map?

      要使用 map,首先需要包含头文件:

      #include <iostream>
      #include <map>   // 使用 map 必须包含这个头文件
      using namespace std;
      

      🧱 三、定义和初始化 map

      ✅ 定义空的 map:

      map<string, int> scores; // 创建一个 map,键是 string 类型,值是 int 类型
      

      ✅ 初始化 map 的几种方式:

      方式1:直接赋值多个键值对(C++11及以上支持)

      map<string, int> scores = {
          {"Alice", 90},
          {"Bob", 85},
          {"Charlie", 95}
      };
      

      方式2:逐个添加元素

      scores["Alice"] = 90;
      scores["Bob"] = 85;
      

      🔍 四、常用操作函数详解 + 示例

      1. 添加/修改元素:[]insert()

      scores["David"] = 88; // 添加一个新键值对
      scores["Alice"] = 95;  // 修改已有的键对应的值
      

      或者使用 insert 方法:

      scores.insert(make_pair("Eve", 92));
      

      2. 访问元素:[]at()

      cout << "Bob 的分数是:" << scores["Bob"] << endl;
      cout << "Alice 的分数是:" << scores.at("Alice") << endl;
      

      ⚠️ 注意:如果使用 at() 访问不存在的键,会抛出异常;而 [] 会自动创建该键并赋予默认值(如int为0)。


      3. 获取 map 中的元素数量:size()

      cout << "当前 map 中有 " << scores.size() << " 个键值对" << endl;
      

      4. 判断是否为空:empty()

      if (scores.empty()) {
          cout << "map 是空的";
      } else {
          cout << "map 不是空的";
      }
      

      5. 删除元素:erase(key)erase(iterator)

      scores.erase("Bob"); // 删除键为 "Bob" 的元素
      
      // 或者通过迭代器删除
      map<string, int>::iterator it = scores.find("Alice");
      if (it != scores.end()) {
          scores.erase(it);
      }
      

      6. 查找元素:find(key)

      map<string, int>::iterator it = scores.find("Charlie");
      if (it != scores.end()) {
          cout << "找到 Charlie,分数是:" << it->second << endl;
      } else {
          cout << "没有找到 Charlie" << endl;
      }
      

      7. 遍历 map

      方法一:使用迭代器

      for(map<string, int>::iterator it = scores.begin(); it != scores.end(); it++) {
          cout << it->first << " : " << it->second << endl;
      }
      

      方法二:使用范围 for 循环(推荐,C++11起)

      for(auto& pair : scores) {
          cout << pair.first << " : " << pair.second << endl;
      }
      

      8. 清空 map:clear()

      scores.clear(); // 所有元素都被清除
      

      📦 五、map 的其他实用功能

      ✅ 检查某个键是否存在

      if (scores.count("David")) {
          cout << "David 存在于 map 中" << endl;
      } else {
          cout << "David 不存在于 map 中" << endl;
      }
      

      ✅ 获取第一个和最后一个元素

      cout << "第一个键值对:" << scores.begin()->first << " : " << scores.begin()->second << endl;
      cout << "最后一个键值对:" << (--scores.end())->first << " : " << (--scores.end())->second << endl;
      

      📌 六、完整示例代码

      #include <iostream>
      #include <map>
      using namespace std;
      
      int main() {
          // 定义并初始化 map
          map<string, int> scores = {
              {"Alice", 90},
              {"Bob", 85},
              {"Charlie", 95}
          };
      
          // 添加元素
          scores["David"] = 88;
      
          // 修改元素
          scores["Alice"] = 95;
      
          // 输出长度
          cout << "当前 map 长度:" << scores.size() << endl;
      
          // 遍历输出
          cout << "当前成绩表:" << endl;
          for(auto& pair : scores) {
              cout << pair.first << " : " << pair.second << endl;
          }
      
          // 查找元素
          if (scores.count("Charlie")) {
              cout << "Charlie 的分数是:" << scores["Charlie"] << endl;
          }
      
          // 删除元素
          scores.erase("Bob");
      
          // 再次遍历输出
          cout << "\n修改后的成绩表:" << endl;
          for(auto& pair : scores) {
              cout << pair.first << " : " << pair.second << endl;
          }
      
          return 0;
      }
      

      📝 七、总结知识点表格

      操作 函数 说明
      添加元素 map[key] = value / insert(pair) 插入或更新键值对
      访问元素 map[key] / at(key) 访问指定键的值
      获取长度 size() 返回键值对数量
      判断是否为空 empty() 是否为空
      删除元素 erase(key) / erase(iterator) 删除指定键或位置的元素
      查找元素 find(key) 返回指向键值对的迭代器
      检查键是否存在 count(key) 返回1(存在)或0(不存在)
      清空所有元素 clear() 清空整个 map

      ✅ 八、学习建议

      • 初学者重点掌握:[]sizefinderasecountinsert
      • 进阶学习:自定义比较函数、使用结构体作为 key、multimap
      • 实战应用:可以用 map 存储字典、统计词频、实现电话簿等
      • @ 2025-5-1 11:25:01

        在 C++ 里,std::map 属于关联容器,它按照键来存储元素,每个键关联着一个值。键具有唯一性,且 std::map 会根据键的顺序对元素进行自动排序。std::map 定义于 <map> 头文件中,其模板定义如下:

        template<
            class Key,
            class T,
            class Compare = std::less<Key>,
            class Allocator = std::allocator<std::pair<const Key, T> >
        > class map;
        

        下面为你详细说明键和值的类型:

        键的类型

        键的类型由模板参数 Key 指定,它必须满足以下要求:

        1. 可比较性:键类型要支持 < 操作符,这是因为 std::map 要借助这个操作符来对元素进行排序。你也可以通过自定义比较函数对象来修改比较规则。
        2. 唯一性:在 std::map 中每个键只能出现一次。

        键可以是任意类型,常见的有:

        • 基本数据类型:像 intdoublechar 这类。
        • 字符串类型:例如 std::string
        • 自定义类型:前提是该类型重载了 < 操作符或者提供了自定义的比较函数对象。

        值的类型

        值的类型由模板参数 T 指定,它没有特别的限制,可以是任意类型,常见的有:

        • 基本数据类型:如 intdoublebool 等。
        • 复合数据类型:例如 std::vectorstd::string、自定义的结构体或者类。

        示例代码

        以下是不同键和值类型组合的示例:

        #include <iostream>
        #include <map>
        #include <string>
        
        // 自定义类作为键类型,需要重载 < 操作符
        class Person {
        public:
            std::string name;
            int age;
        
            Person(const std::string& n, int a) : name(n), age(a) {}
        
            bool operator<(const Person& other) const {
                if (name != other.name) {
                    return name < other.name;
                }
                return age < other.age;
            }
        };
        
        int main() {
            // 键为 int 类型,值为 std::string 类型
            std::map<int, std::string> intToStringMap;
            intToStringMap[1] = "One";
            intToStringMap[2] = "Two";
        
            // 键为 std::string 类型,值为 double 类型
            std::map<std::string, double> stringToDoubleMap;
            stringToDoubleMap["apple"] = 1.5;
            stringToDoubleMap["banana"] = 2.0;
        
            // 键为自定义类型 Person,值为 int 类型
            std::map<Person, int> personToIntMap;
            personToIntMap[Person("Alice", 25)] = 100;
            personToIntMap[Person("Bob", 30)] = 200;
        
            // 输出 intToStringMap
            for (const auto& pair : intToStringMap) {
                std::cout << pair.first << ": " << pair.second << std::endl;
            }
        
            // 输出 stringToDoubleMap
            for (const auto& pair : stringToDoubleMap) {
                std::cout << pair.first << ": " << pair.second << std::endl;
            }
        
            // 输出 personToIntMap
            for (const auto& pair : personToIntMap) {
                std::cout << pair.first.name << " (" << pair.first.age << "): " << pair.second << std::endl;
            }
        
            return 0;
        }
        

        上述代码展示了 std::map 中键和值类型的不同组合,包含基本数据类型、字符串类型以及自定义类型。当使用自定义类型作为键时,需要重载 < 操作符来保证元素能正确排序。

        • @ 2025-5-1 11:10:17
          #include <iostream>
          #include <map>
          #include <string>
          using namespace std;
          int main() {
          	map<string, int> myMap;
          	myMap["apple"] = 10;
          	myMap["banana"] = 20;
          	myMap["cherry"] = 30;
          	
          	// 使用迭代器遍历元素
          	for (map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
          		cout << "Key: " << it->first << ", Value: " << it->second << endl;
          	}
          	for (auto it = myMap.begin(); it != myMap.end(); ++it) {
          		cout << "Key: " << it->first << ", Value: " << it->second << endl;
          	}
          	// C++11 及以上版本可以使用范围 for 循环
          	for (const auto& pair : myMap) {
          		cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
          	}
          	
          	return 0;
          }
          
          
          • @ 2025-5-1 11:03:18
            #include <iostream>
            #include <map>
            #include <string>
            using namespace std;
            int main() {
            	map<string, int> myMap;
            	myMap.insert(make_pair("aaa",99));
            	myMap.insert(pair<string,int>("bbb",9999));
            	pair<string,int>   p1("ccc",9);
            	myMap.insert(p1);
            	myMap["apple"] = 10;
            	myMap["banana"] = 20;
            	myMap["cherry"] = 30;
            	
            	// 使用 [] 运算符访问元素
            	cout << "Value of apple: " << myMap["ccc"] << endl;
            	
            	// 使用 at() 方法访问元素
            	try {
            		cout << "Value of banana: " << myMap.at("bbbbbbb") << endl;
            	} catch (const out_of_range& e) {//超出范围
            //class out_of_range : public logic_error
            //在编程领域,它常作为一种系统异常类型,表示访问的数据超出了合理的范围,比如访问数组或容器中不存在的索引位置。
            		cout << "Element not found: " << e.what() << endl;
            	}
            	
            	return 0;
            }
            
            
            • @ 2025-4-24 21:03:08

              std::map 是 C++ 标准库中一个非常实用的关联容器,它基于红黑树实现,能高效地存储键值对,并且会根据键的大小自动对元素进行排序。下面为你详细介绍 std::map 的使用,包含代码示例与注释。

              1. 包含必要的头文件并使用命名空间

              #include <iostream>
              #include <map>
              // 使用标准命名空间,这样后续使用标准库中的类和函数时无需加 std:: 前缀
              using namespace std; 
              

              2. 定义和初始化 map

              int main() {
                  // 定义一个存储整数键和字符串值的 map
                  map<int, string> myMap;
              
                  // 另一种初始化方式,使用初始化列表
                  map<string, double> priceMap = {
                      {"apple", 2.5},
                      {"banana", 1.8},
                      {"cherry", 3.2}
                  };
              

              在上述代码中,map<int, string> myMap; 定义了一个键为 int 类型,值为 string 类型的 map。而 priceMap 则通过初始化列表在定义时就插入了一些键值对。

              3. 插入元素

                  // 方法一:使用 insert 函数插入键值对
                  myMap.insert(pair<int, string>(1, "One"));
                  myMap.insert(make_pair(2, "Two"));
              
                  // 方法二:使用 [] 运算符插入或更新元素
                  myMap[3] = "Three";
                  // 如果键已经存在,[] 运算符会更新对应的值
                  myMap[1] = "New One"; 
              

              这里展示了两种插入元素的方式。insert 函数可以接受 pair 类型的数据,也可以使用 make_pair 函数来创建键值对。而 [] 运算符更加简洁,如果键不存在则插入新的键值对,如果键已存在则更新对应的值。

              4. 访问元素

                  // 使用 [] 运算符访问元素
                  cout << "键为 2 的值是: " << myMap[2] << endl;
              
                  // 使用 find 函数查找元素
                  auto it = myMap.find(3);
                  if (it != myMap.end()) {
                      cout << "找到键为 3 的元素,值是: " << it->second << endl;
                  } else {
                      cout << "未找到键为 3 的元素" << endl;
                  }
              

              [] 运算符可以方便地通过键来获取对应的值,但如果键不存在,会插入一个默认值的键值对。find 函数返回一个迭代器,如果找到键则指向该键值对,若未找到则返回 myMap.end()

              5. 修改元素

                  // 修改键为 2 的值
                  myMap[2] = "Updated Two";
                  cout << "修改后键为 2 的值是: " << myMap[2] << endl;
              

              使用 [] 运算符可以很方便地修改已存在键对应的值。

              6. 删除元素

                  // 删除键为 1 的元素
                  myMap.erase(1);
                  if (myMap.find(1) == myMap.end()) {
                      cout << "键为 1 的元素已被删除" << endl;
                  }
              

              erase 函数可以根据键来删除 map 中的元素。

              7. 遍历 map

                  // 使用范围 for 循环遍历 map
                  cout << "遍历 myMap:" << endl;
                  for (const auto& pair : myMap) {
                      cout << "键: " << pair.first << ", 值: " << pair.second << endl;
                  }
              
                  // 使用迭代器遍历 priceMap
                  cout << "遍历 priceMap:" << endl;
                  for (auto it = priceMap.begin(); it != priceMap.end(); ++it) {
                      cout << "商品: " << it->first << ", 价格: " << it->second << endl;
                  }
              
                  return 0;
              }
              

              这里展示了两种遍历 map 的方式,范围 for 循环更加简洁直观,而使用迭代器遍历则是一种传统的方式。

              完整代码示例

              #include <iostream>
              #include <map>
              using namespace std;
              
              int main() {
                  // 定义一个存储整数键和字符串值的 map
                  map<int, string> myMap;
              
                  // 另一种初始化方式,使用初始化列表
                  map<string, double> priceMap = {
                      {"apple", 2.5},
                      {"banana", 1.8},
                      {"cherry", 3.2}
                  };
              
                  // 插入元素
                  // 方法一:使用 insert 函数插入键值对
                  myMap.insert(pair<int, string>(1, "One"));
                  myMap.insert(make_pair(2, "Two"));
              
                  // 方法二:使用 [] 运算符插入或更新元素
                  myMap[3] = "Three";
                  // 如果键已经存在,[] 运算符会更新对应的值
                  myMap[1] = "New One"; 
              
                  // 访问元素
                  // 使用 [] 运算符访问元素
                  cout << "键为 2 的值是: " << myMap[2] << endl;
              
                  // 使用 find 函数查找元素
                  auto it = myMap.find(3);
                  if (it != myMap.end()) {
                      cout << "找到键为 3 的元素,值是: " << it->second << endl;
                  } else {
                      cout << "未找到键为 3 的元素" << endl;
                  }
              
                  // 修改元素
                  // 修改键为 2 的值
                  myMap[2] = "Updated Two";
                  cout << "修改后键为 2 的值是: " << myMap[2] << endl;
              
                  // 删除元素
                  // 删除键为 1 的元素
                  myMap.erase(1);
                  if (myMap.find(1) == myMap.end()) {
                      cout << "键为 1 的元素已被删除" << endl;
                  }
              
                  // 遍历 map
                  // 使用范围 for 循环遍历 map
                  cout << "遍历 myMap:" << endl;
                  for (const auto& pair : myMap) {
                      cout << "键: " << pair.first << ", 值: " << pair.second << endl;
                  }
              
                  // 使用迭代器遍历 priceMap
                  cout << "遍历 priceMap:" << endl;
                  for (auto it = priceMap.begin(); it != priceMap.end(); ++it) {
                      cout << "商品: " << it->first << ", 价格: " << it->second << endl;
                  }
              
                  return 0;
              }
              

              总结

              • std::map 是一个有序的关联容器,根据键的大小对元素进行排序。
              • 插入元素可以使用 insert 函数或 [] 运算符。
              • 访问元素可以使用 [] 运算符或 find 函数。
              • 修改元素可以直接使用 [] 运算符。
              • 删除元素使用 erase 函数。
              • 遍历可以使用范围 for 循环或迭代器。
              • 1