fork download
  1. #include <map>
  2. #include <vector>
  3.  
  4. void foo(std::pair<int, int>& p)
  5. {}
  6.  
  7. int main()
  8. {
  9. std::pair<int, int> p{1,2};
  10. foo(p);
  11. std::vector<std::pair<int, int>> v{{1,2}};
  12. for (auto& element : v)
  13. {
  14. foo(element); // works fine
  15. }
  16.  
  17. std::map<int, int> m{std::make_pair(1,2)};
  18. //std::map<int, int> m2{{1,2}};
  19. for (auto& element : m) // the problematic loop
  20. {
  21. foo(element);
  22. }
  23.  
  24. return 0;
  25. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:21:13: error: invalid initialization of non-const reference of type ‘std::pair<int, int>&’ from an rvalue of type ‘std::pair<int, int>’
         foo(element);
             ^~~~~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/6/bits/stl_tree.h:63,
                 from /usr/include/c++/6/map:60,
                 from prog.cpp:1:
/usr/include/c++/6/bits/stl_pair.h:272:19: note:   after user-defined conversion: constexpr std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = const int; _U2 = int; typename std::enable_if<(std::_PCC<((! std::is_same<_T1, _U1>::value) || (! std::is_same<_T2, _U2>::value)), _T1, _T2>::_ConstructiblePair<_U1, _U2>() && std::_PCC<((! std::is_same<_T1, _U1>::value) || (! std::is_same<_T2, _U2>::value)), _T1, _T2>::_ImplicitlyConvertiblePair<_U1, _U2>()), bool>::type <anonymous> = 1u; _T1 = int; _T2 = int]
         constexpr pair(const pair<_U1, _U2>& __p)
                   ^~~~
prog.cpp:4:6: note:   initializing argument 1 of ‘void foo(std::pair<int, int>&)’
 void foo(std::pair<int, int>& p)
      ^~~
stdout
Standard output is empty