C++ map的基本操作和用法

本文详细介绍了C++标准模板库中的map容器,包括其特点、功能以及如何在程序中使用。主要内容涵盖map的基本操作如插入、查找、遍历和删除等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:seanyxie

1、map简介

map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。对于迭代器来说,可以修改实值,而不能修改key。

2、map的功能

自动建立Key - value的对应。key 和 value可以是任意你需要的类型。
根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
快速插入Key - Value 记录。
快速删除记录
根据Key 修改value记录。
遍历所有记录。
3、使用map

使用map得包含map类所在的头文件

#include <map> //注意,STL头文件没有扩展名.h

map对象是模板类,需要关键字和存储对象两个模板参数:

std:map<int, string> personnel;

这样就定义了一个用int作为索引,并拥有相关联的指向string的指针.

为了使用方便,可以对模板类进行一下类型定义,

typedef map<int, CString> UDT_MAP_INT_CSTRING;

UDT_MAP_INT_CSTRING enumMap;

4、在map中插入元素

改变map中的条目非常简单,因为map类已经对[]操作符进行了重载

enumMap[1] = “One”;

enumMap[2] = “Two”;

…..

这样非常直观,但存在一个性能的问题。插入2时,先在enumMap中查找主键为2的项,没发现,然后将一个新的对象插入enumMap,键是2,值是一个空字符串,插入完成后,将字符串赋为”Two”; 该方法会将每个值都赋为缺省值,然后再赋为显示的值,如果元素是类对象,则开销比较大。我们可以用以下方法来避免开销:

enumMap.insert(map<int, CString> :: value_type(2, “Two”))

5、查找并获取map中的元素

下标操作符给出了获得一个值的最简单方法:

CString tmp = enumMap[2];

但是,只有当map中有这个键的实例时才对,否则会自动插入一个实例,值为初始化值。

我们可以使用Find()和Count()方法来发现一个键是否存在。

查找map中是否包含某个关键字条目用find()方法,传入的参数是要查找的key,在这里需要提到的是begin()和end()两个成员,分别代表map对象中第一个条目和最后一个条目,这两个数据的类型是iterator.

int nFindKey = 2; //要查找的Key

//定义一个条目变量(实际是指针)

UDT_MAP_INT_CSTRING::iterator it= enumMap.find(nFindKey);

if(it == enumMap.end()) {

//没找到

}

else {

//找到

}

通过map对象的方法获取的iterator数据类型是一个std::pair对象,包括两个数据 iterator->first 和 iterator->second 分别代表关键字和存储的数据

6、从map中删除元素

移除某个map中某个条目用erase()

该成员方法的定义如下

iterator erase(iterator it); //通过一个条目对象删除
iterator erase(iterator first, iterator last); //删除一个范围
size_type erase(const Key& key); //通过关键字删除
clear()就相当于 enumMap.erase(enumMap.begin(), enumMap.end());

C++ STL map的使用

以下是对C++中STL map的插入,查找,遍历及删除的例子:

#include <map>

#include <string>

include <iostream>

using namespace std;

void map_insert(map < string, string > *mapStudent, string index, string x)
{
mapStudent->insert(map < string, string >::value_type(index, x));
}

int main(int argc, char **argv)
{
char tmp[32] = “”;
map < string, string > mapS;

//insert element
map_insert(&mapS, “192.168.0.128”, “xiong”);
map_insert(&mapS, “192.168.200.3”, “feng”);
map_insert(&mapS, “192.168.200.33”, “xiongfeng”);

map < string, string >::iterator iter;

cout << “We Have Third Element:” << endl;
cout << “—————————–” << endl;

//find element
iter = mapS.find(“192.168.0.33”);
if (iter != mapS.end()) {
cout << “find the elememt” << endl;
cout << “It is:” << iter->second << endl;
} else {
cout << “not find the element” << endl;
}

//see element
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << “| ” << iter->first << ” | ” << iter->
second << ” |” << endl;

}
cout << “—————————–” << endl;

map_insert(&mapS, “192.168.30.23”, “xf”);

cout << “After We Insert One Element:” << endl;
cout << “—————————–” << endl;
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << “| ” << iter->first << ” | ” << iter->
second << ” |” << endl;
}

cout << “—————————–” << endl;

//delete element
iter = mapS.find(“192.168.200.33”);
if (iter != mapS.end()) {
cout << “find the element:” << iter->first << endl;
cout << “delete element:” << iter->first << endl;
cout << “=================================” << endl;
mapS.erase(iter);
} else {
cout << “not find the element” << endl;
}
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << “| ” << iter->first << ” | ” << iter->
second << ” |” << endl;

}
cout << “=================================” << endl;

return 0;
}


查看源代码示例


<think>嗯,用户想了解C++map用法,我需要给他一个基本介绍。首先,我应该从map的基本概念讲起,说明它是关联容器,存储键值对,按键排序。然后要提到它是基于红黑树实现的,这样查询效率高,时间复杂度是O(log n)。 接下来,我应该分点列出常用的成员函数,比如插入数据的几种方法,比如insertemplace,还有用operator[]插入。这里要注意说明operator[]如果键不存在会自动创建,可能会影响数据,所以使用时要注意。 然后遍历部分,用迭代器或者C++11的范围for循环来遍历,示例代码要展示如何输出键值。查找的话,find函数count函数的区别,find返回迭代器,count返回0或1,因为map键唯一。 删除元素可以用erase,参数可以是键或者迭代器。大小清空部分比较简单,size()empty(),clear()。 接下来,可能需要提到C++11引入的emplace函数,说明它insert的区别,比如避免临时对象的构造,提高效率。还有unordered_map的对比,说明map是有序的,而unordered_map是无序但查询更快,基于哈希表。 最后,可以举一个综合示例,把各个操作结合起来,比如统计单词出现次数,这样用户更容易理解实际应用场景。注意示例中的注释要清晰,代码要正确,比如使用emplace插入,范围for遍历,find查找是否存在。 在写作过程中要确保LaTeX格式正确,比如模板中的系统指令提到的数学表达式用$...$,但这里可能用不上,不过代码部分要用正确的格式。另外回答要结构清晰,分点说明,用户可能是初学者,所以语言要简洁明了,避免太专业的术语,必要时解释清楚。 还要检查是否有遗漏的重要点,比如map的键唯一性,multimap的存在,但用户问的是map,所以可以不用深入。另外是否提到性能方面的考虑,比如插入删除的时间复杂度,可能需要简要说明。 确保回答正确,比如operator[]的行为,insert的返回值,这些都是容易出错的地方。最后确认示例代码的正确性,比如使用auto范围for循环是否适合用户的C++版本,可能需要注明需要C++11或以上支持。</think>以下是对C++标准库`std::map`用法的基本介绍(需C++11及以上版本): ### 1. 基本概念 `std::map`是关联容器,存储`键值对(key-value)`,具有以下特性: - 按键自动排序(默认升序) - 每个键唯一(重复插入会失败) - 基于红黑树实现,查询时间复杂度$O(\log n)$ ### 2. 常用成员函数 ```cpp #include <map> using namespace std; map<string, int> m; // 创建map对象 ``` #### 插入数据 ```cpp // 方法1:insert + pair m.insert(pair<string, int>("apple", 5)); // 方法2:emplace(C++11推荐) m.emplace("banana", 3); // 方法3:operator[](若键不存在会自动创建) m["orange"] = 4; ``` #### 遍历元素 ```cpp // 迭代器遍历 for(auto it = m.begin(); it != m.end(); ++it) { cout << it->first << ": " << it->second << endl; } // C++11范围for循环 for(auto& [key, value] : m) { // 结构化绑定(C++17) cout << key << " => " << value << endl; } ``` #### 查找元素 ```cpp auto it = m.find("apple"); if(it != m.end()) { cout << "Found: " << it->second << endl; } // 通过count判断存在性 if(m.count("banana") > 0) { cout << "Exists" << endl; } ``` #### 删除元素 ```cpp m.erase("orange"); // 通过键删除 m.erase(m.begin()); // 通过迭代器删除 m.erase(m.begin(), m.find("apple")); // 删除范围 ``` #### 其他操作 ```cpp m.size(); // 返回元素数量 m.empty(); // 判断是否为空 m.clear(); // 清空容器 ``` ### 3. 注意事项 - 使用`operator[]`访问不存在的键时,会插入默认值 - `insert/emplace`返回值为`pair<iterator, bool>`,第二个参数表示是否插入成功 - C++17支持`try_emplace``insert_or_assign`更安全地操作 ### 4. 示例:单词统计 ```cpp map<string, int> word_count; string word; while(cin >> word) { // 若单词不存在则初始化为0,然后自增 word_count[word]++; } // 输出统计结果 for(const auto& [w, cnt] : word_count) { cout << w << ": " << cnt << endl; } ``` ### 5. 扩展对比 | 特性 | `std::map` | `std::unordered_map` | |-------------------|-------------------|----------------------| | 实现方式 | 红黑树 | 哈希表 | | 元素顺序 | 按键排序 | 无序 | | 查询时间复杂度 | $O(\log n)$ | $O(1)$(平均) | | 内存占用 | 较低 | 较高 | | 适用场景 | 需要有序遍历 | 快速查找 | 建议根据具体需求选择容器类型,当需要保持元素有序时使用`map`,优先考虑查找速度时使用`unordered_map`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值