Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as key in map C ++

Basically, I need to find all matching anagrams to a word. What I was doing was using an array of size 26 to represent the letters in a word. Ex:

abcdefg={1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
aaaaaaa={7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}

This is how I'm creating the array.

//stringtemp is a C++ string representing the word.
//letters is a size 26 int array representing all the letters in the string.
for(int i=0;i<stringtemp.length();i++)
{
    letters[stringtemp[i]-65]+=1;
}

And this is how I'm storing the array in the map.

dictionary[letters].push_back(stringtemp);

So, am I doing something wrong or is this impossible in C++. In all the other answers I found, they suggested to use a vector as the key, but that won't work in my case(I think.)

like image 980
user1525047 Avatar asked Feb 16 '26 13:02

user1525047


1 Answers

All of std::array<T, 26>, std::string and std::vector<T> are perfectly valid key types for a std::map, since they all define less-than comparison operators. Note that std::array<T, 26> is similar to std::tuple<T, T, ..., T>, and comparison is defined lexicographically, very similar to string comparison.

#include <array>
#include <map>

typedef std::array<unsigned int, 26> alphabet;

std::map<alphabet, std::string> dictionary;

dictionary[{{1, 0, ..., 8}}] = "hello";

With a bit more work, you can also make all of those types keys for an std::unordered_map, though you'll have to add a bit of boilerplate code from Boost (using hash_combine).

like image 84
Kerrek SB Avatar answered Feb 19 '26 05:02

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!