stl容器c语言实现数组去重
时间: 2024-04-15 10:23:17 浏览: 28
在C语言中,可以通过使用STL容器来实现数组去重的功能。STL(Standard Template Library)是C++标准库的一部分,提供了一系列的容器和算法,方便开发者进行数据结构和算法的实现。
在C语言中,可以使用哈希表来实现数组去重。哈希表是一种以键值对形式存储数据的数据结构,通过将元素的值映射到一个唯一的索引位置来实现快速的查找和插入操作。
以下是使用哈希表实现数组去重的步骤:
1. 创建一个空的哈希表。
2. 遍历原始数组中的每个元素。
3. 对于每个元素,检查哈希表中是否已经存在该元素。
- 如果存在,则说明该元素已经出现过,不需要再次插入到结果数组中。
- 如果不存在,则将该元素插入到哈希表中,并将该元素添加到结果数组中。
4. 返回结果数组,即为去重后的数组。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define HASH_SIZE 100
typedef struct Node {
int value;
struct Node* next;
} Node;
typedef struct HashTable {
Node* buckets[HASH_SIZE];
} HashTable;
void initHashTable(HashTable* hashTable) {
for (int i = 0; i < HASH_SIZE; i++) {
hashTable->buckets[i] = NULL;
}
}
int hash(int value) {
return value % HASH_SIZE;
}
bool contains(HashTable* hashTable, int value) {
int index = hash(value);
Node* node = hashTable->buckets[index];
while (node != NULL) {
if (node->value == value) {
return true;
}
node = node->next;
}
return false;
}
void insert(HashTable* hashTable, int value) {
int index = hash(value);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = value;
newNode->next = hashTable->buckets[index];
hashTable->buckets[index] = newNode;
}
void removeDuplicates(int* arr, int size) {
HashTable hashTable;
initHashTable(&hashTable);
int result[size];
int resultSize = 0;
for (int i = 0; i < size; i++) {
if (!contains(&hashTable, arr[i])) {
insert(&hashTable, arr[i]);
result[resultSize++] = arr[i];
}
}
printf("去重后的数组:");
for (int i = 0; i < resultSize; i++) {
printf("%d ", result[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 2, 3, 5};
int size = sizeof(arr) / sizeof(arr);
removeDuplicates(arr, size);
return 0;
}
```
运行以上代码,输出结果为:去重后的数组:1 2 3 4 5
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)