Reputation: 111
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that.
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]();
Upvotes: 0
Views: 941
Reputation: 19118
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.
- 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
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)
.
Upvotes: 2