Shiva Chandel
Shiva Chandel

Reputation: 111

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.

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

Answers (2)

erenon
erenon

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

Raj Sheth
Raj Sheth

Reputation: 33

You can use following line of code:

hash[ar[i]] += 1

Upvotes: 0

Related Questions