![](/img/trans.png)
[英]Hash Table implementation in C++ - How to return a key with a particular value
[英]How to increment a particular value of a hash table without changing its key?
我正在遍历数字数组(0-9),并希望将其存储在哈希表中。
int ar[size]={0,2,0,1,4,6,8 ........ 8,6,7}; // array
auto hash=new int[10]; //here the value is initialized to zero
for(int i=0;i<size;i++)
{
//here i want to store the time a number occurred in the array with
keys as number itself
hash[ar[i]] = **valueof(hash[ar[i]])+1** // i want to do this
}
编辑
auto hash=new int[10]();
您可以在适当位置增加值:
hash[ar[i]]++;
也:
// Not true:
auto hash=new int[10]; //here the value is initialized to zero
您必须添加一个初始化程序:
auto hash=new int[10](); //here the value is initialized to zero
参考:
如果type是数组类型,则初始化对象数组。
- 如果没有初始化程序,则每个元素都将默认初始化
- 如果初始值设定项是一对空括号,则每个元素都将被值初始化。
https://en.cppreference.com/w/cpp/language/new
同样,并不需要真正的堆分配,您可以简单地使用int hash[10] = {0}
或std::array<int, 10> hash; hash.fill(0)
std::array<int, 10> hash; hash.fill(0)
。
您可以使用以下代码行:
hash[ar[i]] += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.