LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 2

Modifying a map through auto& structured bindings Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> score{{"asha", 10}, {"ravi", 20}};
    for (auto [name, s] : score) s += 5;            // copies
    for (auto& [name, s] : score) s *= 2;           // references
    auto& [k, v] = *score.begin();
    v = 1;
    for (const auto& [name, s] : score) std::cout << name << s << ' ';
    std::cout << '\n';
    return 0;
}
  • A asha1 ravi40 Correct
  • B asha30 ravi50
  • C asha1 ravi50
  • D asha20 ravi40
Correct Answer: Option A

auto [..] binds to a copy of each pair; auto& [..] to the real elements. The last binding refers to the first map element.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links