介绍
在本实验中,我们将创建一个 C++ 程序来演示 STL 中无序多重集合(Unordered Multiset)的工作原理。我们将学习无序多重集合的概念及其在 C++ 编程语言中的实现。
在本实验中,我们将创建一个 C++ 程序来演示 STL 中无序多重集合(Unordered Multiset)的工作原理。我们将学习无序多重集合的概念及其在 C++ 编程语言中的实现。
在这一步中,我们将为程序包含必要的头文件。我们将包含 iostream
和 unordered_set
头文件。
#include<iostream>
#include<unordered_set>
using namespace std;
在这一步中,我们将定义两个函数来显示无序多重集合(Unordered Multiset)和向量(Vector)的内容。
void showMultiset(unordered_multiset<int> s)
{
unordered_multiset<int>::iterator i;
for (i = s.begin(); i != s.end(); i++)
{
cout << *i << " ";
}
}
void showVector(vector<int> v)
{
vector<int>::iterator i;
for (i = v.begin(); i != v.end(); i++)
{
cout << *i << " ";
}
}
在这一步中,我们将声明一个无序多重集合(Unordered Multiset),并使用 insert()
方法填充一些元素。
unordered_multiset<int> s;
s.insert(50);
s.insert(30);
s.insert(50);
s.insert(80);
s.insert(30);
s.insert(60);
在这一步中,我们将使用 showMultiset()
函数和 size()
方法显示无序多重集合(Unordered Multiset)及其大小。
cout << "\n\nThe number of elements in the Unordered Multiset are: " << s.size();
cout << "\n\nThe elements of the Unordered Multiset are: ";
showMultiset(s);
在这一步中,我们将无序多重集合(Unordered Multiset)的元素复制到一个向量(Vector)中,并对向量进行排序。然后,我们将使用 showVector()
函数显示排序后的无序多重集合元素。
vector<int> v(s.begin(), s.end());
sort(v.begin(), v.end());
cout << "\n\nThe elements of the Unordered Multiset after sorting using a vector are: ";
showVector(v);
在这一步中,我们将通过使用 g++
命令编译代码,然后使用 ./a.out
命令执行它来运行代码。
g++ main.cpp -o main && ./main
输出结果应为:
The number of elements in the Unordered Multiset are: 6
The elements of the Unordered Multiset are: 50 30 80 50 30 60
The elements of the Unordered Multiset after sorting using a vector are: 30 30 50 50 60 80
在本实验中,我们学习了无序多重集合(Unordered Multiset)的概念及其在 C++ 中使用 STL 库的实现。我们了解了如何声明和初始化无序多重集合、如何显示其内容,以及如何使用向量对其进行排序。
希望你享受这个实验,并发现它对学习 C++ 中的无序多重集合有所帮助。