写个集合出来,用C#代码
时间: 2023-12-08 13:03:39 浏览: 23
语言实现。
这里是一个简单的集合实现示例:
```
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int size;
} Set;
void init_set(Set *s)
{
s->size = 0;
}
void add_element(Set *s, int element)
{
if (s->size < MAX_SIZE) {
s->data[s->size++] = element;
} else {
printf("Set is full!\n");
}
}
bool contains(Set *s, int element)
{
for (int i = 0; i < s->size; i++) {
if (s->data[i] == element) {
return true;
}
}
return false;
}
void remove_element(Set *s, int element)
{
int i;
for (i = 0; i < s->size; i++) {
if (s->data[i] == element) {
break;
}
}
if (i < s->size) {
for (int j = i; j < s->size - 1; j++) {
s->data[j] = s->data[j+1];
}
s->size--;
} else {
printf("Element not found!\n");
}
}
int main()
{
Set s;
init_set(&s);
add_element(&s, 1);
add_element(&s, 2);
add_element(&s, 3);
printf("Set contains 2: %d\n", contains(&s, 2));
printf("Set contains 4: %d\n", contains(&s, 4));
remove_element(&s, 2);
printf("Set contains 2: %d\n", contains(&s, 2));
printf("Set contains 3: %d\n", contains(&s, 3));
return 0;
}
```
这个集合实现使用了一个结构体来存储集合的数据。`init_set`函数用来初始化集合,`add_element`函数用来向集合中添加元素,`contains`函数用来检查集合中是否包含给定元素,`remove_element`函数用来从集合中删除给定元素。在`main`函数中,我们创建了一个集合`s`,向其中添加了三个元素,然后检查集合中是否包含某些元素,最后从集合中删除了一个元素。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)