Monday, November 13, 2017

C++17: for (auto [key, value] : my_map) {…})

C++17 allows you to get key and values nicely in a ranged-base for loop. Here is an example:

#include <iostream>
#include <map>
#include <string>

int main()
{
  std::map<int, std::string> myMap{{1,"a"}, {2, "b"}, {3, "c"}};

  for (auto [key, value] : myMap)
  {
    std::cout << key << " " << value << " : ";
  }

  std::cout << std::endl;
  return 0;
}
// Output: 1 a : 2 b : 3 c :
Reference: https://www.infoq.com/news/2017/10/cpp-17-herb-sutter-interview

No comments:

Post a Comment