c++中有关哈希表的STL操作

15 篇文章 0 订阅
本文介绍了红黑树和无序集合(unordered_set)及映射(unordered_map)的基础知识。红黑树是一种自平衡二叉查找树,插入、删除和查找操作的时间复杂度为O(logn),适用于有序数据操作。而unordered_set和unordered_map基于哈希表实现,提供O(1)的平均时间复杂度,适合快速查找和插入但不保证顺序。文中列举了它们常用的操作函数,并提及了迭代器的使用方法。
摘要由CSDN通过智能技术生成
  1. set
    基于红黑树实现,可以进行去重和排序操作。O(logn)。
    一些常用的函数有:

    s.insert(x);
    s.erase(x);
    s.size();
    s.find(x);
    s.count(x); //因为有去重性质,count()统计出现的次数要么是0,要么是1,可以替代find()
    s.empty();

  2. unordered_set
    O(1)。
    一些常用的函数:

    s.insert();
    s.erase();
    s.find();
    s.count();
    s.empty();

  3. map<string, int>
    一种键值对的映射关系,内部存储结构是pair<first, second> 。[first-key,second-value]。前面的元素字典序排列
    一些常见操作函数:

    m.size();
    m.insert(pair);
    m.find(key);
    m.count(key);
    m.erase(key);
    m[key] = value;

  4. unordered_map<key, value>
    无序版的map。
    一些常用的操作函数:

    m.size();
    m.insert(pair);
    m.find(key);
    m.count(key);
    m.erase(key);
    m[key] = value;

迭代器

for (auto it = m.begin(); it != m.end(); it ++ )
{
	cout << it->first << " " << it->second << endl;
}
要在C++实现哈希表,可以通过以下步骤进行: 1. 定义一个哈希函数,将键(key)映射到哈希表的索引。哈希函数应该是高效的,尽可能地减少哈希冲突。 2. 定义一个数组,用于存储哈希表的元素(键值对)。 3. 在数组插入一个元素时,先使用哈希函数计算出该元素的索引,然后将元素插入到该索引处。如果该索引处已经有元素,则需要解决哈希冲突,例如使用开放寻址法或链表法。 4. 在数组查找一个元素时,同样使用哈希函数计算出该元素的索引,然后在该索引处查找元素。如果该索引处没有元素,则说明该元素不在哈希表。 以下是一个简单的示例代码,演示了如何实现一个基本的哈希表,其使用了开放寻址法来解决哈希冲突: ```c++ #include <iostream> const int TABLE_SIZE = 128; class HashTable { private: struct Node { int key; int value; bool is_deleted; // 标记是否被删除 }; Node table[TABLE_SIZE]; // 哈希函数 int hash(int key) const { return key % TABLE_SIZE; } public: HashTable() { for (int i = 0; i < TABLE_SIZE; ++i) { table[i].key = -1; table[i].value = -1; table[i].is_deleted = false; } } // 插入元素 void insert(int key, int value) { int index = hash(key); while (table[index].key != -1 && table[index].is_deleted == false) { // 线性探测 index = (index + 1) % TABLE_SIZE; } table[index].key = key; table[index].value = value; table[index].is_deleted = false; } // 查找元素 int find(int key) const { int index = hash(key); while (table[index].key != -1) { if (table[index].key == key && table[index].is_deleted == false) { return table[index].value; } index = (index + 1) % TABLE_SIZE; } return -1; } // 删除元素 void remove(int key) { int index = hash(key); while (table[index].key != -1) { if (table[index].key == key && table[index].is_deleted == false) { table[index].is_deleted = true; return; } index = (index + 1) % TABLE_SIZE; } } }; int main() { HashTable ht; ht.insert(1, 10); ht.insert(2, 20); ht.insert(3, 30); std::cout << ht.find(2) << std::endl; // 输出 20 ht.remove(2); std::cout << ht.find(2) << std::endl; // 输出 -1 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值