21xrx.com
2024-09-20 00:49:03 Friday
登录
文章检索 我的文章 写文章
C++中的map函数是如何定义和使用的?
2023-07-05 06:18:34 深夜i     --     --
C++ Map函数 定义 使用 键值对

C++是一门面向对象的编程语言,其中的STL(Standard Template Library)库是其重要的组成部分之一。STL中的map是一种关联式容器,可以将键值对储存在其中。在C++中,map被定义在头文件中,其语法如下:


std::map<key_type, value_type> map_name;

其中key_type表示键的数据类型,value_type表示值的数据类型,map_name则表示map容器的名称。

使用map容器时,可以使用insert()函数将键值对插入map中,使用find()函数查找键对应的元素并返回对应的迭代器,使用erase()函数删除指定的键值对,并使用size()函数获取map容器的大小。

以下是一个简单的使用示例:


#include <iostream>

#include <map>

int main() {

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

  students.insert(std::make_pair("Tom", 80));

  students.insert(std::make_pair("Alice", 90));

  students["Bob"] = 85; // 使用下标操作符添加元素

  students.erase("Tom"); // 按照键名删除元素

  std::map<std::string, int>::iterator it = students.find("Alice");

  if (it != students.end())

    std::cout << "Alice's score is: " << it->second << std::endl;

  

  std::cout << "The size of students map is: " << students.size() << std::endl;

  return 0;

}

输出结果为:


Alice's score is: 90

The size of students map is: 2

在这个示例中,我们创建了一个名为students的map容器,其中存储了三个学生的姓名和成绩。我们使用insert()函数插入了Tom和Alice的信息,使用下标操作符来添加Bob的信息。接着使用erase()函数删除了Tom的信息,并使用find()函数查找Alice的信息并输出。最后,使用size()函数获取容器的大小并输出。

总的来说,C++中的map容器提供了一种简洁、高效的存储和访问键值对数据的方法,是C++语言以及STL库的重要组成部分之一。

  
  

评论区

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