21xrx.com
2024-09-19 09:23:08 Thursday
登录
文章检索 我的文章 写文章
如何在C++的map中使用emplace函数来插入自定义类型元素?
2023-07-02 08:43:40 深夜i     --     --
C++ map emplace函数 自定义类型 插入元素

在C++中,map是一种高效的关联容器,它可以存储键和值之间的映射关系。通常情况下,我们可以使用insert函数来将元素插入map中,但是在某些情况下,使用emplace函数可能更加方便和有效。本文将介绍如何在C++的map中使用emplace函数来插入自定义类型元素。

首先,让我们看一下使用insert函数来插入自定义类型元素的代码示例:


#include <iostream>

#include <map>

#include <string>

struct Student

  std::string name;

  int age;

;

int main() {

  std::map<std::string, Student> students;

  Student s1"Tom";

  students.insert(std::make_pair("001", s1));

  Student s2 19;

  students.insert(std::make_pair("002", s2));

  for (auto& s : students)

    std::cout << s.first << " " << s.second.name << " " << s.second.age << std::endl;

  

  return 0;

}

在上面的代码中,我们定义了一个名为Student的结构体来表示学生信息,并创建了一个名为students的map,其中键为学生的编号,值为学生信息。我们使用insert函数将两个学生信息插入到map中,并最后遍历输出所有的学生信息。

接下来,我们将使用emplace函数重写上面的代码示例:


#include <iostream>

#include <map>

#include <string>

struct Student

  std::string name;

  int age;

;

int main() {

  std::map<std::string, Student> students;

  students.emplace("001", Student 18);

  students.emplace("002", Student"Jerry");

  for (auto& s : students)

    std::cout << s.first << " " << s.second.name << " " << s.second.age << std::endl;

  

  return 0;

}

在上面的代码中,我们使用emplace函数来将两个学生信息插入到map中。与insert函数不同的是,emplace函数可以在调用时直接构造元素,而不需要我们先手动构造元素,然后再把它们传给insert函数。

总结一下,在C++的map中使用emplace函数来插入自定义类型元素可以简化代码,同时也可以提高效率。我们只需要在调用emplace函数时,直接传入元素的构造参数即可。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复