简体   繁体   中英

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]();

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) std::array<int, 10> hash; hash.fill(0) .

您可以使用以下代码行:

hash[ar[i]] += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM