C++ 关联式容器map 与 set 的原理与实践操作
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、关联式容器的核心概念</li><ul class="second_class_ul"><li>1. 容器分类与特点</li><li>2. 底层实现</li><li>3. 搜索模型</li></ul><li>二、set 的原理与使用</li><ul class="second_class_ul"><li>1. set 的核心特性</li><li>2. set 的常用操作</li><ul class="third_class_ul"><li>(1)插入操作</li><li>(2)遍历操作</li><li>(3)删除操作</li><li>(4)查找操作</li></ul><li>3. set 的实际应用</li><ul class="third_class_ul"></ul></ul><li>三、map 的原理与使用</li><ul class="second_class_ul"><li>1. map 的核心特性</li><ul class="third_class_ul"></ul><li>2. map 的常用操作</li><ul class="third_class_ul"><li>(1)pair 类型介绍</li><li>(2)插入操作</li><li>(3)遍历操作</li><li>(4)查找与修改操作</li><li>(5)删除操作</li></ul><li>3. map 的实际应用</li><ul class="third_class_ul"></ul></ul><li>四、map 与 set 的区别与联系</li><ul class="second_class_ul"><li>1. 相同点</li><ul class="third_class_ul"></ul><li>2. 不同点</li><ul class="third_class_ul"></ul></ul><li>五、使用注意事项</li><ul class="second_class_ul"></ul><li>六、总结</li><ul class="second_class_ul"></ul></ul></div><p> 在 C++ 中,容器是存放数据的重要数据结构,分为序列式容器和关联式容器。序列式容器(如 vector、list、deque)按线性顺序存储元素,元素的位置与值无关;而关联式容器则通过键(key)建立元素间的关联,实现高效的查找、插入和删除操作。本文将详细介绍关联式容器中最常用的 <strong>map</strong> 和 <strong>set</strong>,包括它们的底层实现、核心特性、使用方法及实际应用。</p><p class="maodian"></p><h2>一、关联式容器的核心概念</h2>
<p class="maodian"></p><h3>1. 容器分类与特点</h3>
<p> 关联式容器的核心是 “关联关系”,即通过键(key)快速定位元素,而无需像序列式容器那样遍历整个容器。其特点如下:</p>
<ul><li>元素按特定规则排序(有序容器)或无序存储(无序容器);</li><li>插入位置由元素的键决定,而非用户指定;</li><li>查找效率极高,平均时间复杂度为 O(logN)(有序容器)或 O(1)(无序容器)。</li></ul>
<p class="maodian"></p><h3>2. 底层实现</h3>
<p> 有序容器(set、map 等)的底层通常采用 <strong>平衡二叉搜索树(红黑树)</strong> 实现,其特性为:</p>
<ul><li>左子树所有节点的值 < 根节点的值;</li><li>右子树所有节点的值 > 根节点的值;</li><li>树的高度保持平衡,确保查找、插入、删除操作的时间复杂度为 O(logN)。</li></ul>
<p> 无序容器(unordered_set、unordered_map 等)的底层采用 <strong>哈希表</strong> 实现,通过哈希函数将键映射到存储位置,平均时间复杂度为 O(1),但最坏情况下可能退化为 O(N)。</p>
<p class="maodian"></p><h3>3. 搜索模型</h3>
<p> 关联式容器分为两种搜索模型:</p>
<ul><li><strong>K 模型</strong>:仅存储键(key),如 set,核心功能是判断元素是否存在;</li><li><strong>KV 模型</strong>:存储键值对(key-value),如 map,核心功能是通过键查找对应的值。</li></ul>
<p class="maodian"></p><h2>二、set 的原理与使用</h2>
<p class="maodian"></p><h3>1. set 的核心特性</h3>
<p> set 是 <strong>有序、不重复</strong> 的 K 模型容器,底层为红黑树。其核心特性:</p>
<ul><li>自动排序:插入元素后,容器会按键的升序(默认)排列;</li><li>自动去重:插入重复元素时,操作会失败,容器中仅保留一个实例;</li><li>不可修改元素:set 中的元素是 const 类型,修改元素会破坏红黑树的结构,需通过 “删除旧元素 + 插入新元素” 实现。</li></ul>
<p class="maodian"></p><h3>2. set 的常用操作</h3>
<p class="maodian"></p><h4>(1)插入操作</h4>
<p> set 不支持 push_back/push_front,需使用 <code>insert()</code> 插入元素:</p>
<div class="jb51code"><pre class="brush:cpp;">#include <set>
using namespace std;
set<int> s;
s.insert(3);
s.insert(1);
s.insert(3); // 重复插入,操作失败</pre></div>
<p> 插入后,set 中的元素会自动排序为 <code>{1, 3}</code>。</p>
<p class="maodian"></p><h4>(2)遍历操作</h4>
<p>set 支持迭代器遍历和范围 for 遍历:</p>
<div class="jb51code"><pre class="brush:cpp;">void test(){
set<int> s;
s.insert(3);
s.insert(4);
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(7);
//排序+去重
set<int>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
it++;
}
cout << endl;
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
}
</pre></div>
<p class="maodian"></p><h4>(3)删除操作</h4>
<p> set 支持两种删除方式:</p>
<ul><li>通过迭代器删除(需先通过 <code>find()</code> 查找元素);</li><li>直接通过值删除。</li></ul>
<div class="jb51code"><pre class="brush:cpp;">// 方式 1:通过迭代器删除
set<int>::iterator pos = s.find(7); //log(N)
//set<int>::iterator pos = find(s.begin(), s.end(), 4); //OP(N)
if (pos != s.end())
{
s.erase(pos);
}
// 方式 2:直接通过值删除
s.erase(1);// 删除元素 1,若不存在则无操作</pre></div>
<p class="maodian"></p><h4>(4)查找操作</h4>
<p> set 的查找功能是其核心,提供两种方式:</p>
<ul><li>成员函数 <code>find()</code>:利用红黑树特性,时间复杂度 O(logN);</li><li>算法 <code>std::find()</code>:线性遍历,时间复杂度 O(N)。</li></ul>
<p><strong>示例对比</strong>:</p>
<div class="jb51code"><pre class="brush:cpp;">#include <algorithm>// 包含 std::find
// 成员函数 find()
set<int>::iterator pos1 = s.find(3);// 高效查找
// 算法 find()
set<int>::iterator pos2 = find(s.begin(), s.end(), 3);// 低效遍历</pre></div>
<p><strong>使用建议</strong>:优先使用 set 的成员函数 <code>find()</code> 以获得最佳性能。</p>
<p class="maodian"></p><h3>3. set 的实际应用</h3>
<p> set 的核心优势是 <strong>快速存在性检查</strong> 和 <strong>高效去重排序</strong>,适用于以下场景:</p>
<ul><li>存储学号、身份证号等唯一标识,快速验证是否存在;</li><li>对输入数据去重并排序,如统计考试成绩的不重复分数;</li><li>实现集合运算(交集、并集、差集)。</li></ul>
<p><strong>示例:验证学号是否存在</strong></p>
<div class="jb51code"><pre class="brush:cpp;">student_ids.insert("001");
student_ids.insert("002");
student_ids.insert("003");
string id = "002";
if (student_ids.find(id) != student_ids.end()) {
cout << "学号 " << id << " 存在" << endl;
} else {
cout << "学号 " << id << " 不存在" << endl;
}</pre></div>
<p class="maodian"></p><h2>三、map 的原理与使用</h2>
<p class="maodian"></p><h3>1. map 的核心特性</h3>
<p> map 是 <strong>有序、键唯一</strong> 的 KV 模型容器,底层为红黑树。其核心特性:</p>
<ul><li>存储键值对(key-value),键(key)唯一,值(value)可重复;</li><li>按键自动排序(默认升序);</li><li>通过键快速查找对应的值,时间复杂度 O(logN);</li><li>支持通过键修改值,但键不可修改(否则会破坏红黑树结构)。</li></ul>
<p class="maodian"></p><h3>2. map 的常用操作</h3>
<p class="maodian"></p><h4>(1)pair 类型介绍</h4>
<p> map 中的元素是 <code>pair<const key_type, value_type></code><strong> </strong>类型,<code>pair</code> 是一个模板结构体,包含两个成员:</p>
<ul><li><code>first</code>:键(key),不可修改;</li><li><code>second</code>:值(value),可修改。</li></ul>
<p>创建 <code>pair</code> 的方式:</p>
<div class="jb51code"><pre class="brush:cpp;">// 方式 1:显式指定模板参数
pair<int, string> p1(1, "张三");
// 方式 2:使用 make_pair(自动推导类型)
pair<int, string> p2 = make_pair(2, "李四");</pre></div>
<p class="maodian"></p><h4>(2)插入操作</h4>
<p> map 通过 <code>insert()</code> 插入 <code>pair</code> 类型元素:</p>
<div class="jb51code"><pre class="brush:cpp;">#include <map>
using namespace std;
map<int, string> student_info;
// 方式 1:插入 pair 对象
student_info.insert(pair<int, string>(1, "张三"));
// 方式 2:使用 make_pair(推荐,更简洁)
student_info.insert(make_pair(2, "李四"));
// 方式 3:C++11 统一初始化
student_info.insert({3, "王五"});</pre></div>
<p> 插入后,map 会按键的升序排列:<code>{1:张三, 2:李四, 3:王五}</code>。</p>
<p class="maodian"></p><h4>(3)遍历操作</h4>
<p> map 支持迭代器遍历和范围 for 遍历,通过 <code>it->first</code> 访问键,<code>it->second</code> 访问值:</p>
<div class="jb51code"><pre class="brush:cpp;">// 迭代器遍历
map<int, string>::iterator it = student_info.begin();
while (it != student_info.end()) {
cout << "学号:" << it->first << ",姓名:" << it->second << endl;
++it;
}
// 范围 for 遍历
for (auto e : student_info) {
cout << "学号:" << e.first << ",姓名:" << e.second << endl;
}</pre></div>
<p class="maodian"></p><h4>(4)查找与修改操作</h4>
<p> 通过键查找值有两种方式:</p>
<ul><li>成员函数 <code>find()</code>:返回指向该键值对的迭代器;</li><li>下标运算符 <code>[]</code>:直接通过键访问值(若键不存在,会自动插入一个默认构造的键值对)。</li></ul>
<div class="jb51code"><pre class="brush:cpp;">// 方式 1:find() 查找(推荐,避免误插入)
map<int, string>::iterator pos = student_info.find(2);
if (pos != student_info.end()) {
cout << "找到:" << pos->second << endl;// 输出:李四
pos->second = "李小四";// 修改值
}
// 方式 2:下标访问(注意:键不存在时会自动插入)
string name = student_info;// 访问键 3 的值,存在则返回 "王五"
student_info = "赵六"; // 键 4 不存在,插入 {4:赵六}</pre></div>
<p class="maodian"></p><h4>(5)删除操作</h4>
<p> map 的删除方式与 set 类似,支持迭代器删除和键删除:</p>
<div class="jb51code"><pre class="brush:cpp;">// 方式 1:通过迭代器删除
map<int, string>::iterator pos = student_info.find(2);
if (pos != student_info.end()) {
student_info.erase(pos);
}
// 方式 2:通过键删除
student_info.erase(3);// 删除键 3 对应的键值对</pre></div>
<p class="maodian"></p><h3>3. map 的实际应用</h3>
<p> map 的核心优势是 <strong>通过键快速查找值</strong>,适用于以下场景:</p>
<ul><li>存储键值对映射关系,如字典(单词 - 翻译)、学号 - 成绩;</li><li>统计元素出现次数,如统计字符串中每个单词的出现次数;</li><li>实现缓存机制(键为缓存 key,值为缓存数据)。</li></ul>
<p><strong>示例:统计字符串出现次数</strong></p>
<div class="jb51code"><pre class="brush:cpp;">string str[] = { "西瓜","圣女果", "圣女果", "西瓜", "西瓜", "香蕉", "葡萄", "葡萄", "菠萝", "西瓜", "桃子", "西瓜","栗子", "水蜜桃", "西瓜", "葡萄" };
map<string, int> countMap;
for (auto e : str)
{
map<string, int>::iterator pos = countMap.find(e);
if (pos == countMap.end())
countMap.insert(make_pair(e, 1));
else
pos->second++;
}
for (auto e : countMap)
{
cout << e.first<<":"<<e.second<<endl;
}</pre></div>
<p class="maodian"></p><h2>四、map 与 set 的区别与联系</h2>
<p class="maodian"></p><h3>1. 相同点</h3>
<ul><li>底层均为红黑树(有序容器),操作时间复杂度均为 O(logN);</li><li>均支持自动排序和去重(set 去重键,map 去重键);</li><li>均不支持直接修改元素(set 元素不可修改,map 键不可修改)。</li></ul>
<p class="maodian"></p><h3>2. 不同点</h3>
<table><thead><tr><th>特性</th><th>set</th><th>map</th></tr></thead><tbody><tr><td>存储类型</td><td>仅键(K 模型)</td><td>键值对(KV 模型)</td></tr><tr><td>核心功能</td><td>快速存在性检查</td><td>快速键值映射查找</td></tr><tr><td>元素访问</td><td>仅访问键</td><td>访问键和值</td></tr><tr><td>修改方式</td><td>不可修改,需删插</td><td>可修改值,键不可改</td></tr></tbody></table>
<p class="maodian"></p><h2>五、使用注意事项</h2>
<ol><li><strong>元素不可修改</strong>:set 的元素和 map 的键均为 const 类型,修改会破坏红黑树结构,需通过 “删插” 实现;</li><li><strong>迭代器有效性</strong>:插入元素时,红黑树可能重新平衡,迭代器不会失效;删除元素时,仅被删除元素的迭代器失效,其他迭代器有效;</li><li><strong>比较规则</strong>:默认按键的升序排序,若需自定义排序,可在定义容器时指定比较函数(如 <code>set<int, greater<int>></code> 按降序排序);</li><li><strong>效率选择</strong>:<ul><li>需有序存储且高效查找时,使用 set/map;</li><li>无需排序且追求极致查找效率时,使用 unordered_set/unordered_map(哈希表实现);</li><li>仅需线性存储时,使用 vector/list 等序列式容器。</li></ul></li></ol>
<p class="maodian"></p><h2>六、总结</h2>
<p> map 和 set 是 C++ 中最常用的关联式容器,其核心优势在于 <strong>高效的查找、插入和删除操作</strong>,底层依赖红黑树实现有序存储和去重。set 专注于 “键的存在性检查”,map 专注于 “键值对的映射查找”,二者在实际开发中应用广泛,如数据去重、统计计数、字典映射等场景。</p>
<p> 掌握 map 和 set 的使用,需理解其底层实现原理和核心特性,根据实际需求选择合适的容器,以优化程序性能。</p>
<p>到此这篇关于C++ 关联式容器map 与 set 的原理与实践操作的文章就介绍到这了,更多相关c++ map和set原理内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>C++map,set,multiset,multimap详细解析</li><li>C++实现map和set封装详解</li><li>C++中map和set的使用及示例</li><li>C++中map和set封装实现示例</li><li>c++容器list、vector、map、set区别与用法详解</li><li>C++中map和set的使用示例详解</li><li>C++ 用红黑树模拟实现set、map的示例代码</li><li>C++用一棵红黑树同时封装出set与map的实现代码</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]