定义一个元素类型为int、元素个数不受限制的集合类Set。除了定义一些必要的函数外,必须定义具有以下功能的成员函数。
时间: 2023-06-07 13:09:44 浏览: 113
1. 插入元素:将一个新元素插入到集合中(若已存在该元素,则不插入)。
2. 删除元素:从集合中删除一个指定元素(若不存在该元素,则不进行操作)。
3. 判断元素是否在集合中:判断一个指定元素是否在集合中存在。
4. 集合大小:返回集合中元素的个数。
5. 清空集合:清空集合中所有元素。
下面是一个简单的代码示例:
```
class Set {
public:
Set() {}
~Set() {}
void insert(int num);
void remove(int num);
bool contains(int num);
int size();
void clear();
private:
unordered_set<int> s; // 使用 unordered_set 存储元素
};
void Set::insert(int num) {
s.insert(num);
}
void Set::remove(int num) {
s.erase(num);
}
bool Set::contains(int num) {
return s.find(num) != s.end();
}
int Set::size() {
return s.size();
}
void Set::clear() {
s.clear();
}
```
相关问题
定义一个元素类型为int,元素个数不受限制的集合类Inset
好的,按照您的要求,我来定义一个元素类型为int,元素个数不受限制的集合类Inset,该类具有以下的接口:
```c++
class Inset {
public:
// 插入一个元素
virtual void insert(int x) = 0;
// 删除一个元素
virtual void erase(int x) = 0;
// 判断元素是否存在
virtual bool contains(int x) const = 0;
// 获取元素个数
virtual int size() const = 0;
// 清空集合
virtual void clear() = 0;
};
```
这里我们使用了纯虚函数,即定义了一个抽象类 Inset,它只是定义了接口,具体的实现由子类来完成。这样做的好处是,我们可以根据实际需求来创建不同的集合类,比如可以使用哈希表、红黑树等不同的数据结构来实现。
定义并实现一个元素类型为int,元素个数不受限制的集合类Inset
好的,下面是一个使用哈希表实现的元素类型为int,元素个数不受限制的集合类Inset的定义和实现:
```c++
#include <iostream>
#include <unordered_set>
class Inset {
public:
// 插入一个元素
void insert(int x) {
set.insert(x);
}
// 删除一个元素
void erase(int x) {
set.erase(x);
}
// 判断元素是否存在
bool contains(int x) const {
return set.count(x);
}
// 获取元素个数
int size() const {
return set.size();
}
// 清空集合
void clear() {
set.clear();
}
private:
std::unordered_set<int> set;
};
int main() {
Inset mySet;
// 插入元素
mySet.insert(1);
mySet.insert(2);
mySet.insert(3);
// 删除元素
mySet.erase(2);
// 判断元素是否存在
std::cout << "mySet contains 1: " << mySet.contains(1) << std::endl;
std::cout << "mySet contains 2: " << mySet.contains(2) << std::endl;
// 获取元素个数
std::cout << "mySet size: " << mySet.size() << std::endl;
// 清空集合
mySet.clear();
return 0;
}
```
这里我们使用了 C++ STL 中的 unordered_set,它是一种基于哈希表实现的集合容器。我们只需要实现 Inset 类中的接口,并在内部使用 unordered_set 进行实现即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)