介绍
在本实验中,我们将学习 C++ STL Map 容器中的 erase()
方法,以删除 C++ 编程语言中 Map 中的一系列元素。
在本实验中,我们将学习 C++ STL Map 容器中的 erase()
方法,以删除 C++ 编程语言中 Map 中的一系列元素。
在 ~/project
目录下使用命令 touch ~/project/main.cpp
创建一个名为 main.cpp
的新 C++ 文件,并使用你喜欢的文本编辑器打开它。
在这一步中,我们将创建一个 map 并使用 insert()
方法填充整数键值对。make_pair()
函数用于将键值对插入到 map 中。键会自动按升序排序。
#include <iostream>
#include <map>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the working of erase() method in a Map (Part 2), in CPP ===== \n\n\n";
map<int, int> m;
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(9, 90));
m.insert(make_pair(1, 10));
}
在这一步中,我们将使用 erase()
方法删除 map 中键小于某个值的元素。在这个例子中,我们将删除所有键小于 3 的元素。erase(m.begin(), m.find(3))
会从 map 的开头删除元素,直到指向键为 3 的元素的迭代器位置。
#include <iostream>
#include <map>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the working of erase() method in a Map (Part 2), in CPP ===== \n\n\n";
map<int, int> m;
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(9, 90));
m.insert(make_pair(1, 10));
cout << "Map elements before deletion: " << endl;
for (auto i : m)
{
cout << "( " << i.first << ", " << i.second << " ) ";
}
m.erase(m.begin(), m.find(3));
cout << "\n\nMap elements after deletion: " << endl;
for (auto i : m)
{
cout << "( " << i.first << ", " << i.second << " ) ";
}
cout << "\n\n\n";
return 0;
}
要运行上述 C++ 代码,我们需要在终端中使用以下命令进行编译和执行:
g++ ~/project/main.cpp -o ~/project/main && ~/project/./main
成功编译并执行上述代码后,输出结果如下:
Welcome to LabEx :-)
===== Program to demonstrate the working of erase() method in a Map (Part 2), in CPP =====
Map elements before deletion:
( 1, 10 ) ( 2, 20 ) ( 3, 30 ) ( 5, 50 ) ( 9, 90 )
Map elements after deletion:
( 3, 30 ) ( 5, 50 ) ( 9, 90 )
在本实验中,我们学习了 C++ STL Map 容器中的 erase()
方法,用于删除 C++ 编程语言中 Map 中的一系列元素。我们还学习了如何使用 insert()
方法创建 Map 并填充键值对。最后,我们了解了如何使用 erase()
从 Map 中删除元素。