[英]How to increment a particular value of a hash table without changing its key?
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that. 我正在遍历数字数组(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
}
Edit 编辑
auto hash=new int[10]();
You can increment the value in place: 您可以在适当位置增加值:
hash[ar[i]]++;
Also: 也:
// Not true:
auto hash=new int[10]; //here the value is initialized to zero
You have to add a initializer: 您必须添加一个初始化程序:
auto hash=new int[10](); //here the value is initialized to zero
Reference: 参考:
If type is an array type, an array of objects is initialized. 如果type是数组类型,则初始化对象数组。
- If initializer is absent, each element is default-initialized 如果没有初始化程序,则每个元素都将默认初始化
- If initializer is an empty pair of parentheses, each element is value-initialized. 如果初始值设定项是一对空括号,则每个元素都将被值初始化。
https://en.cppreference.com/w/cpp/language/new https://en.cppreference.com/w/cpp/language/new
Also, the heap allocation is not really needed, you could simply use int hash[10] = {0}
or std::array<int, 10> hash; hash.fill(0)
同样,并不需要真正的堆分配,您可以简单地使用int hash[10] = {0}
或std::array<int, 10> hash; hash.fill(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.