简体   繁体   中英

Cannot iterate map through auto in C++

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.

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM