I've been trying to insert a string into a hashmap called 'keys' that uses arrays as the key values. The commented out lines use a vector instead of an array as the key. When I use a vector instead of an array, the code works perfectly as intended. However, I want to find out if it's possible to use an array of a fixed size to solve the problem instead. If anyone can demonstrate how, I would greatly appreciate it!
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
map<array<int,26>,vector<string>> keys;
// map<vector<int>,vector<string>> keys;
for(auto x:strs){
int count[26];
// vector<int> count(26,0);
for(auto c:x){
count[c-'a'] ;
}
keys[count].emplace_back(x);
}
for(auto k = keys.begin(); k != keys.end(); k ){
res.emplace_back(k->second);
}
return res;
}
};
Here's the error I get:
Line 13: Char 17: error: no viable overloaded operator[] for type 'map<array<int, 26>, vector<std::string>>' (aka 'map<array<int, 26>, vector<basic_string<char>>>')
keys[count].emplace_back(x);
~~~~^~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_map.h:490:7: note: candidate function not viable: no known conversion from 'int [26]' to 'const std::map<std::array<int, 26>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, std::less<std::array<int, 26>>, std::allocator<std::pair<const std::array<int, 26>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>::key_type' (aka 'const std::array<int, 26>') for 1st argument
operator[](const key_type& __k)
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_map.h:510:7: note: candidate function not viable: no known conversion from 'int [26]' to 'std::map<std::array<int, 26>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, std::less<std::array<int, 26>>, std::allocator<std::pair<const std::array<int, 26>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>::key_type' (aka 'std::array<int, 26>') for 1st argument
operator[](key_type&& __k)
^
1 error generated.
CodePudding user response:
For std::map, you need to implement <
less than comparator to make it work for key insertion. So probably a free function like bool operator <(const auto &array1, const auto &array2)
with your logic on sorting the arrays should make the insertion work.
Might also need to provide equality (==) overload (but can not remember if it is required or not) for retrieval.
CodePudding user response:
is also defined as one of the less-than operators which we can use in , so its quite simple to use them. You should consider the way how you are trying to access or assign the map.Here's an example for your convenience.
Blockquote map<array<int,26>,string> ex; ex[{{4,5,6}}] = "whatever";