Home > Blockchain >  How to store array data as map key or increment frequency if array already in map?
How to store array data as map key or increment frequency if array already in map?

Time:07-03

My code:

map<array<byte, aes>, int> possible;
array<byte,aes> temp;

if (!possible.count(temp)) // if not found
    possible.insert(pair<array<byte,aes>,int>(temp,1)); // insert
else
    possible[temp]  ; // if found increment frequency

I need to use an array with its data as a map key. An integer indicates the frequency of occurrence of the array. However, the new array is only written the first time, the other times the code considers it to be the same array. As I understand it, the program takes the address of the array, not its data. How to pass an array with data to the map instead of the address of the array? I know that in Qt this code works fine:

QMap<QByteArray,int> possible;
QByteArray temp;
if(!possible.count(temp)) // if not found
    possible.insert(temp, 1); // insert
else
    possible[temp]  ; // if found increment frequency

What is alternative for std::array and std::map to do this?

CodePudding user response:

In C this code will work fine

possible[temp]  ;

If temp exists then it's frequency will be incremented. If it does not exist then it will be inserted with a frequency of 0, which will then be incremented. This gives you exactly the same result as your code.

Looking at the documentation for QMap, it seems the above code would also work on Qt.

Sometimes (not often) things are easier than you imagined.

  • Related