I have some dynamic int * arrays that I would like to use as keys for an unordered_map. I’m a bit unclear on how I should declare the key type so it would actually be the value of the entire array.
Also, to deallocate the memory for the arrays, do I use map.clear()?
Example:
unordered_map<??, int> frequency;
while (some_condition) {
int *my_array = new int[size];
putSomeValuesToArray(my_array);
frequency[my_array]++;
}
// to deallocate memory for the arrays in frequency?
You won’t be able to stick
int*as key inside astd::mapand still be able to retrieve elements ‘by value’. The reason for that is a singleint*only provides the start of an array, you need the end too to compute anything (equivalently and more C-like, the length). In other words,int*does not an array (dynamic or otherwise) make; in this context it’s an iterator to the start of a sequence.You can use
std::pair<int*, int*>but it should only be used for non-owning ‘views’ of data. That is, if you manually manage memory with astd::map<std::pair<int*, int*>, int>you’ll end up with a headache. One possibility is using a smart-pointer:std::pair<std::unique_ptr<int[]>, int*>. But as others have recommended, just usestd::vectoras it is still compatible with C-like interfaces that deal withint*. Plus aconst std::pair<std::unique_ptr<int>, int*>still allows you to scribble the memory, which can mess up the ordering of the map and ends you up in trouble.A final blow to using
int*orstd::unique_ptr<int[]>is that you would need to provide the strict weak ordering thatstd::maprequires, whereasstd::vector<int>comes with an appropriateoperator<. On the other hand, you need to provide a hash for both if you settle instead onstd::unordered_map. For what it’s worth, a simple functor that usesstd::lexicographical_compare(same semantics asstd::vectorcomparison):Then you can use
std::map<std::pair<std::unique_ptr<int[]>, int*>, int, compare>.