Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c++ - use of std::less in std::map does not compile

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?

question from:https://stackoverflow.com/questions/65880956/use-of-stdless-in-stdmap-does-not-compile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

myMap can 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 a std::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 a std::less<int>.


In the second program, replacing () with {} resolves the ambiguity. Now myMap can no longer be a function declaration, and so it instead declares a variable of type std::map<int, int, std::less<int>>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...