C++ 使用 STL Map 中的 find 方法

C++Beginner
立即练习

介绍

在本实验中,你将学习如何在 C++ 的 Map 中使用 find() 方法。find() 方法用于在 Map 中根据给定的键搜索元素。本实验假设你已经具备 C++ 和 Map 容器的基本知识。

创建一个新的 C++ 文件

首先,你需要在 ~/project 目录下创建一个名为 main.cpp 的 C++ 文件。你可以使用任何文本编辑器或 IDE 来创建和编辑此文件。

cd ~/project
touch main.cpp

包含必要的库和命名空间

main.cpp 文件的顶部,包含必要的库和使用指令。

#include <iostream>
#include <map>   //包含 map 库

using namespace std;

定义主函数

定义 main() 函数以开始编写你的代码。

int main() {
  //你的代码
  return 0;   //退出程序
}

创建一个 Map 容器

创建一个键和值均为整数的 Map 容器。Map 容器将存储按键升序排序的键值对。

map<int, int> myMap;   //创建一个键和值均为整数的 Map 容器

向 Map 中插入元素

使用 insert() 方法将键值对插入到 Map 容器中。此步骤将向 Map 中插入五个元素。

myMap.insert(make_pair(3, 9));
myMap.insert(make_pair(2, 4));
myMap.insert(make_pair(5, 25));
myMap.insert(make_pair(9, 81));
myMap.insert(make_pair(1, 1));

使用 find() 方法搜索元素

使用 find(x) 方法在 Map 中搜索键为 x 的元素。如果找到该元素,方法将返回指向该元素的迭代器。如果未找到,方法将返回指向 Map 容器 end() 的迭代器。在这里,我们将搜索键为 5 和 6 的元素。

map<int, int>::iterator it;   //为 Map 容器创建一个迭代器
it = myMap.find(5);   //在 Map 中查找键为 5 的元素
if (it != myMap.end()) {
  cout << "Element with key 5 is found and the value is " << it->second << endl;
} else {
  cout << "Element with key 5 is not found\n";
}
it = myMap.find(6);   //在 Map 中查找键为 6 的元素
if (it != myMap.end()) {
  cout << "Element with key 6 is found and the value is " << it->second << endl;
} else {
  cout << "Element with key 6 is not found\n";
}

编译并运行程序

在终端中使用以下命令编译 main.cpp 文件:

g++ main.cpp -o main

使用以下命令运行程序:

./main

测试程序

运行程序后,你应该会在终端中看到以下输出:

Element with key 5 is found and the value is 25
Element with key 6 is not found

此输出表明,键为 5 的元素在 Map 中被找到,其值为 25。而键为 6 的元素在 Map 中未找到。

完成代码

将以下完整代码复制并粘贴到 main.cpp 文件中。

#include <iostream>
#include <map>

using namespace std;

int main() {
  map<int, int> myMap;   //创建一个键和值均为整数的 Map 容器
  myMap.insert(make_pair(3, 9));
  myMap.insert(make_pair(2, 4));
  myMap.insert(make_pair(5, 25));
  myMap.insert(make_pair(9, 81));
  myMap.insert(make_pair(1, 1));
  map<int, int>::iterator it;   //为 Map 容器创建一个迭代器
  it = myMap.find(5);   //在 Map 中查找键为 5 的元素
  if (it != myMap.end()) {
    cout << "Element with key 5 is found and the value is " << it->second << endl;
  } else {
    cout << "Element with key 5 is not found\n";
  }
  it = myMap.find(6);   //在 Map 中查找键为 6 的元素
  if (it != myMap.end()) {
    cout << "Element with key 6 is found and the value is " << it->second << endl;
  } else {
    cout << "Element with key 6 is not found\n";
  }
  return 0;   //退出程序
}

总结

恭喜!你已经成功学会了如何在 C++ 的 Map 容器中使用 find() 方法。find() 方法在 Map 容器中用于搜索具有特定键的元素非常有用。请记住,如果找到元素,find() 方法会返回指向该元素的迭代器;如果未找到元素,则返回指向 Map 容器 end() 的迭代器。