介绍
在本实验中,你将学习 Multiset(多重集合)的工作原理及其在 C++ 编程语言中的实现。你将特别学习如何在 Set 或 Multiset 中使用 erase()
方法来删除元素。
在本实验中,你将学习 Multiset(多重集合)的工作原理及其在 C++ 编程语言中的实现。你将特别学习如何在 Set 或 Multiset 中使用 erase()
方法来删除元素。
使用你选择的任何文本编辑器,在项目目录 ~/project
中创建一个名为 main.cpp
的 C++ 代码文件。
cd ~/project
touch main.cpp
将以下代码输入到 main.cpp
文件中。注释部分解释了代码的功能。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// 使用迭代器打印 multiset 元素的函数
void show(multiset<int> s)
{
// 声明一个迭代器用于遍历 multiset
multiset<int>::iterator i;
for (i = s.begin(); i != s.end(); i++)
{
cout << *i << " "; // 使用 * 访问 multiset 的元素,因为 i 存储的是每个元素的地址
}
cout << endl;
}
int main()
{
cout << "\n\nWelcome to STL Set erase() Method Lab\n\n\n";
cout << " ===== Program to demonstrate the working of a Multiset, in CPP ===== \n\n\n\n";
cout << "*** Multisets 类似于 set,但允许多个元素具有相同的值。*** \n\n";
// 声明一个 multiset(整数集合)
multiset<int> s;
// 使用 insert() 方法填充元素
cout << "\n\n以随机顺序向 Multiset 中填充整数。"; // Multiset 会自动按顺序存储它们
s.insert(5);
s.insert(39);
s.insert(5);
s.insert(82);
s.insert(39);
s.insert(54);
cout << "\n\nMultiset 中的元素数量为: " << s.size();
cout << "\n\nMultiset 中的元素为: ";
show(s);
multiset<int>::iterator it;
// 删除所有小于 54 的元素
s.erase(s.begin(), s.find(54));
cout << "\n\n删除所有小于 54 的元素后,Multiset 变为: ";
for (it = s.begin(); it != s.end(); it++)
{
cout << " " << *it;
}
cout << "\n\n\n";
return 0;
}
在终端中,使用 g++
命令编译 main.cpp
文件,然后运行编译后的文件。
g++ main.cpp -o main && ./main
你应该会看到以下输出:
Welcome to STL Set erase() Method Lab
===== Program to demonstrate the working of a Multiset, in CPP =====
花点时间仔细阅读代码,确保你理解如何使用 erase()
方法从 Multiset 中删除元素。
// 删除所有小于 54 的元素
s.erase(s.begin(), s.find(54));
这段代码使用 erase()
方法删除 Multiset 中从开始到值等于 54 的元素(不包括值为 54 的元素)。因此,最终的 Multiset 仅包含值 54 和 82。
在本实验中,你学习了如何在 C++ 的 Set 或 Multiset 中使用 erase()
方法删除元素。你还学习了如何使用迭代器遍历 multiset,并通过 show()
方法打印元素。这在调试或检查复杂数据结构(如 Set 和 Multiset)的内容时非常有用。