Per https://en.cppreference.com/w/cpp/container/unordered_map/insert, the insert method "inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key."
The call to insert in the following section won't actually change the contents of the unordered_map.
if (map.find(arr[i]) != map.end()) {
auto freq = map.find(arr[i])->second;
freq++;
map.insert(pair<int, int> (arr[i], freq)); // <<-- here
}
Option 1: Make freq a reference
if (map.find(arr[i]) != map.end()) {
auto& freq = map.find(arr[i])->second;
freq++;
}
Option 2: Simplify the algorithm,
unordered_map<int, int> collectMap(const vector<int>& arr) {
unordered_map<int, int> map;
for (int val : arr) {
++map[val];
}
return map;
}
Answer from MarkB on Stack OverflowVideos
Per https://en.cppreference.com/w/cpp/container/unordered_map/insert, the insert method "inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key."
The call to insert in the following section won't actually change the contents of the unordered_map.
if (map.find(arr[i]) != map.end()) {
auto freq = map.find(arr[i])->second;
freq++;
map.insert(pair<int, int> (arr[i], freq)); // <<-- here
}
Option 1: Make freq a reference
if (map.find(arr[i]) != map.end()) {
auto& freq = map.find(arr[i])->second;
freq++;
}
Option 2: Simplify the algorithm,
unordered_map<int, int> collectMap(const vector<int>& arr) {
unordered_map<int, int> map;
for (int val : arr) {
++map[val];
}
return map;
}
To quote cppreference:
Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.
You should probably use operator[] instead.
I have a degree in ECE but I haven't written any code in about 4 years. I have an exam for an embedded systems role I applied for, but it doesn't have any rules listed.
Would I typically be allowed to google things during this test? That's pretty much how I've always coded because I always get syntax and functions mixed up between languages. I definitely couldn't answer the sample question without googling C documentation.