C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ map插入

C++ map插入方式详解及find使用方法

作者:Tianwen_Burning

这段文章详细介绍了C++中std::map的四种插入方式及其特点,包括使用下标运算符[]、emplace、insert和pair等方法,并解释了为何结构体需要无参构造函数以兼容所有插入方式,感兴趣的朋友一起看看吧

1. map的四种插入方式

在C++中,std::map 提供了多种插入元素的方式。以下是四种常用的插入方法:

1.1 使用下标运算符[](最简单)

map1[0] = student(101, "j");

特点:

1.2 使用emplace(C++11推荐)

map1.emplace(60, student(222, "d"));

特点:

1.3 使用insert和初始化列表(最易懂)

map1.insert({900, student(500, "rr")});

特点:

1.4 使用insert和pair(最详细但啰嗦)

map1.insert(pair<int, student>(70, student(2000, "bad")));

特点:

2. find的使用方法

find 方法用于在map中查找指定键的元素:

2.1 基本用法

// 查找键为50的元素
auto it = map1.find(50);

if (it != map1.end()) {
    // 找到了,可以访问元素
    cout << "找到元素: " << it->second.name << endl;
} else {
    // 没找到
    cout << "未找到键为50的元素" << endl;
}

2.2 查找并修改

auto it = map1.find(100);
if (it != map1.end()) {
    // 修改找到的元素
    it->second.name = "修改后的名字";
    it->second.scor = 9999;
}

2.3 查找并删除

auto it = map1.find(60);
if (it != map1.end()) {
    map1.erase(it);  // 删除找到的元素
}

3. 结构体需要无参构造函数的原因

当map的值为结构体时,结构体必须有无参构造函数,原因如下:

3.1 下标运算符[]的要求

map1[0] = student(101, "j");

这行代码实际上执行了两个步骤:

  1. map1[0] - 如果键0不存在,会创建一个默认构造的student对象
  2. = student(101, "j") - 然后将这个默认对象替换为新对象

如果没有无参构造函数,第一步就会失败。

3.2 结构体定义示例

struct student {
    int scor;
    string name;
    
    // 必须有无参构造函数
    student() {
        scor = 0;
        name = "";
    };
    
    // 带参数的构造函数
    student(int scor0, string name0) {
        scor = scor0;
        name = name0;
    };
};

3.3 替代方案

如果不想提供无参构造函数,可以使用以下插入方式:

// 使用insert或emplace,避免使用[]
map1.insert({0, student(101, "j")});
map1.emplace(0, student(101, "j"));

4. 总结对比

插入方式语法简洁度效率键存在时的行为是否需要无参构造函数
map[key] = value★★★★★较低覆盖原有值
emplace()★★★★☆最高不插入
insert({key, value})★★★★☆不插入
insert(pair<>)★★☆☆☆不插入

建议:

到此这篇关于C++ map插入方式详解及find使用方法的文章就介绍到这了,更多相关C++ map插入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文