【发布时间】:2021-04-29 00:48:03
【问题描述】:
我无法理解为什么以下函数无法编译
#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;
}
报错信息如下-
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;
虽然后续编译成功
#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;
}
有人可以帮我解决这个问题吗?
【问题讨论】:
-
如何编译失败?实际的错误信息是什么?在构造
std::less对象时,使用()和{}应该没有区别。 -
@RemyLebeau 这就是我的想法。但似乎并非如此。我已经编辑了带有错误消息的问题。
-
您是否有理由一开始就明确使用
std::less?它已经是std::map的默认比较器,因此您无需在此代码中显式使用它:std::map<int, int> myMap; -
@RemyLebeau 我正在使用 std::less 来重现错误。在我的实际代码中,我使用的是自定义比较器。
标签: c++ c++11 constructor most-vexing-parse