【发布时间】:2021-07-23 06:54:14
【问题描述】:
这是我收到错误的基本代码 sn-p:
错误:将“const std::map
”作为“this”参数传递会丢弃限定符 [-fpermissive]`
struct Point {
float x;
float y;
int id;
Point(float x, float y, float id) : x(x), y(y), id(id) {}
};
void removePoints(std::vector<Point> &points_vec) {
std::map<int, bool> my_map;
for (const auto& pt : points_vec) {
if(pt.id < 0)
my_map[pt.id] = true;
else
my_map[pt.id] = false;
}
points_vec.erase(std::remove_if(points_vec.begin(), points_vec.end(), [map_lambda = my_map] (const Point pt) -> bool {
return map_lambda[pt.id];
}), points_vec.end());
}
int main(int argc, char const *argv[]) {
std::vector<Point> points_vec;
points_vec.push_back(Point(1, 2, 0));
points_vec.push_back(Point(1, 5, -1));
points_vec.push_back(Point(3, 3, -1));
points_vec.push_back(Point(4, 9, 2));
points_vec.push_back(Point(0, 1, 3));
points_vec.push_back(Point(-1, 7, -2));
std::cout << points_vec.size() << std::endl;
removePoints(points_vec);
std::cout << points_vec.size() << std::endl;
return 0;
}
注意:我知道我可以不使用std::map 删除点,但上面的代码 sn-p 只是一个更大问题的示例。
我检查了一些关于类似错误的问题:
- error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
- C++ "error: passing 'const std::map<int, std::basic_string<char> >' as 'this' argument of ..."
但在他们两个中,这是因为std::map 已被声明为const。另一方面,我尝试使用/访问的map 尚未声明为const,我的错误也与lambda 有关。如您所见,我在 lambda 捕获列表中将原始 my_map 的副本创建为 map_lambda = my_map。那么,为什么我会收到这个 -fpermissive 错误?或者,当我们在 lambda 中捕获某些内容时,它是否会自动转换为 const?
详细的错误信息:
main.cpp: In lambda function:
main.cpp:26:32: error: passing ‘const std::map<int, bool>’ as ‘this’ argument discards qualifiers [-fpermissive]
return map_lambda[pt.id];
^
In file included from /usr/include/c++/7/map:61:0,
from main.cpp:2:
/usr/include/c++/7/bits/stl_map.h:484:7: note: in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = bool; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, bool> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = bool; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’
operator[](const key_type& __k)
^~~~~~~~
顺便说一句,我知道operator[] 如果键已经存在则返回值,否则它会创建一个新键并插入值(并返回它)。但是为什么const for std::map::operator[] 会出现编译错误呢?它不应该更像是运行时错误吗?
【问题讨论】:
标签: c++ dictionary c++11 lambda stl