一. hash_map
使用STL标准库时,如不了解其实现细节,很容易写出错误的代码。常见操作如遍历容器时时同时删除元素,见代码:
#include <ext/hash_map> using namespace __gnu_cxx; // linux使用hash_map必须使用该命名空间 hash_map<int,Person*> hash; Person *per = NULL; hash_map<int,Person*>::iterator it; for( it=hash.begin();it!=hash.end();it++ ) { per = it->second; if( per->age == 20 ) { hash.erase( it ); // 删除年龄为20的节点 } }
上面代码运行几次后,突然就崩溃了。hash_map内部采用哈希表实现,迭代器其实就是指向节点的指针,在访问下一个节点时通过it++移动到下一个节点的地址。执行erase(it)后,it成为一个非法指针,执行it++就会出错。正确的使用方式应该在删除节点前,将指针移到下一个正确地址上。
// 正确写法 for( it=hash.begin();it!=hash.end(); ) { per = it->second; if( per->age == 20 ) { hash.erase( it++ ); // 方法一:执行it++指向下一个节点 //it = hash.erase( it ); // 方法二:接收erase()返回值 } else { it++; } }
二. Java容器
Java中操作list,set,map容器时,经常会抛出 ConcurrentModificationException 异常。
// 错误写法 Iterator<String> it = list.iterator(); while( it.hasNext() ){ String val = it.next(); if( val == "boy" ) { list.remove(val); // 删除元素boy } }
有兴趣可以分析list实现源码,在遍历时执行remove()导致迭代器内部记录变量值不一致所致。正确的写法使用Iterator.remove()。
// 正确写法,调用迭代器删除方法 it = list.iterator(); while( it.hasNext() ){ String val = it.next(); // 删除元素boy if( val == "girl" ) { it.remove(); // 内部也是调用list.remove(),只不过多了对变量值的修正操作 } }
相关推荐
关于hash_map的用法与解释: #include <hash_map> #include #include using namespace std; //define the class class ClassA{ public: ClassA(int a):c_a(a){} int getvalue()const { return c_a;} void ...
hash_map
linux 下hash_map的基本原理及使用,希望对大家有帮助。
代码重点是hash_table,附加std::map与其做对比,实现的是一条sql语句:select c_nationkey, c_mktsegment, count(*), max(c_acctbal) from aaa_customer_1g group by c_nationkey, c_mktsegment order by c_...
TBB 并发容器 concurrent_queue concurrent_vector concurrent_hash_map TBB 并发容器 concurrent_queue concurrent_vector concurrent_hash_map TBB 并发容器 concurrent_queue concurrent_vector concurrent_hash_...
一个用Hash算法实现的map,可以实际项目所使用。 希望能帮助大家学习。
本实例实现了一个hash_map,key是string类型,即可以存储索引是string的数据,希望对大家有帮助
jg :: dense_hash_map 一个简单的std::unordered_map替代品,具有更好的性能,但失去了稳定的寻址方式,这是一种折衷方案。 在此处查看此哈希图的详细说明: : 生成状态: 特拉维斯(Travis):
结合Java的HashMap中的一些优点,改进了C++ 的hash_map。 详细说明见我的博客:http://blog.csdn.net/mdj67887500/article/details/6907702
hash_map基于hash table(哈希表)。 哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,几乎可以看成是常数时间;而代价仅仅是消耗比较多的内存。然而在当前可利用内存越来越多的情况下,用空间换时间...
很久以来,STL中都只提供<map>作为存放对应关系的容器,内部通常用红黑树实现,据说原因是二叉平衡树(如红黑树)的各种操作,插入、删除、查找等,都是稳定的时间复杂度,即O(log n);但是对于hash表来说,由于无法...
STL hash_map: 链式散列 版权所有 (c) 2014,龙 (Ryan) 南宫。 保留所有权利。 邮箱: 创建时间:2014 年 7 月 15 日 这是无序的哈希映射,它具有恒定的插入、删除、搜索时间,并支持向前/向后迭代。 hash_map 的...
Hash值查看以及修改软件(Hash_1.0.4_0523.exe以及HashModifier.exe),网盘必备工具。
MD5校验Hash_1.0.4 轻松复制各个参数 检验软件安全性
文件MD5查看 Hash_1.0.4_XiaZaiBa.exe
asp版hmac_sha1加密方式,支持中英文,真正和PHP的hash_hmac加密结果完全一样,与java、php、python、js 一致,附对比。支持中文utf-8编码
Hash_1.0.4.exe检验文件Hash,
stm32f407平台上实现的hash算法
哈希计算器,可以计算文件的MD5、SHA1和CRC32值。它支持文件拖放,速度很快