Reputation: 119
I am trying to iterate this simple through auto feature but it is giving me tons of errors. I don't know what's wrong with this code.
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
int main() {
std::unordered_map<std::string, int> m = {
{"apples", 5},
{"bananas", 3},
{"pears", 7},
};
for (auto& [fruit, count] : m) { //line 13
std::cout << "I have " << count << " " << fruit << ".\n";
}
}
13 [Error] expected unqualified-id before '[' token13
14 [Error] expected ';' before '[' token
13 [Error] 'fruit' was not declared in this scope
13 [Error] 'count' was not declared in this scope
And many more errors. I have read this example online and it is working fine there.
Upvotes: 3
Views: 540
Reputation: 12263
Structured bindings are a C++17 feature.
Iterating through the std::unordered_map
in C++11 would look something like:
for (auto const& p : m) {
std::cout << "I have " << p.second << " " << p.first << ".\n";
}
Upvotes: 3