I am unable to understand why does following function not compile
#include <iostream>
#include <map>
int main(){
std::map<int, int, std::less<int>> myMap(std::less<int>());
myMap[2] = 2;
std::cout << myMap[2] << std::endl;
return 0;
}
The error message is as follows -
std_less_check.cpp: In function ‘int main()’:
std_less_check.cpp:6:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
myMap[2] = 2;
^
std_less_check.cpp:6:14: error: assignment of read-only location ‘*(myMap + 2)’
myMap[2] = 2;
^
std_less_check.cpp:6:14: error: cannot convert ‘int’ to ‘std::map<int, int, std::less<int> >(std::less<int> (*)())’ in assignment
std_less_check.cpp:7:23: warning: pointer to a function used in arithmetic [-Wpointer-arith]
std::cout << myMap[2] << std::endl;
while following compiles successfully
#include <iostream>
#include <map>
int main(){
std::map<int, int, std::less<int>> myMap(std::less<int>{});
myMap[2] = 2;
std::cout << myMap[2] << std::endl;
return 0;
}
Could someone please help me with this?
In the first program, you have a vexing parse. If the compiler can parse a declaration as either a variable or a function, it will choose to parse it as a function.
myMapcan be parsed as a function declaration.It returns a
std::map<int, int, std::less<int>>.It takes an argument of type
std::less<int>(), which is itself a function type that returns astd::less<int>and takes no arguments. Note that you can't actually have a function type as an argument; the type is actually a pointer to a function that takes no arguments and returns astd::less<int>.In the second program, replacing
()with{}resolves the ambiguity. NowmyMapcan no longer be a function declaration, and so it instead declares a variable of typestd::map<int, int, std::less<int>>.