在stl_algorithm .h中比较指针时出错
Error in stl_algo.h, comparing pointers
我试图找出对象是否存在于指针向量中。
vector<Objectoid*> elements;
bool contains(Objectoid &o){
for(int i = 0; i < elements.size(); i++){
if(elements[i] == &o){
return true;
}
}
return false;
}
但是得到这些错误,
no match for 'operator==' in '__first. __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Objectoid**, _Container = std::vector<Objectoid*, std::allocator<Objectoid*> >]() == __value'
in stl_algo.h
.
非常感谢你的帮助。
编辑:完整代码
class Cell : public Element{
public:
Rectf cellRect;
Vec2i size;
Vec2i pos;
vector<Objectoid*> elements;
Cell(Vec2f &pos_, Vec2f &size_){
pos = pos_;
size = size_;
Vec2f p2 = Vec2f(pos.x + size.x, pos.y + size.y);
cellRect = Rectf(pos, p2);
}
void add(Objectoid &o){
elements.push_back(&o);
}
void remove(Objectoid &o){
elements.erase(std::remove(elements.begin(), elements.end(), o), elements.end());
}
bool contains(Objectoid &o){
for(int i = 0; i < elements.size(); i++){
if(elements[i] == &o){
return true;
}
}
return false;
}
};
我正在尝试在2D游戏中实现碰撞检测的哈希表。这是表中每个单元格的类。
编辑
所以罪魁祸首实际上是
void remove(Objectoid &o){
elements.erase(std::remove(elements.begin(), elements.end(), o), elements.end());
}
首先,一个注释:您现在提供了一些我们可以编译的东西,这很有帮助。也就是说,有一堆代码不是问题的一部分(例如你的构造函数),我们实际上不能编译你所呈现的代码(Vec2i
没有定义)。
第二,回答你的问题: Clang提供以下错误:
/usr/include/c++/4.2.1/bits/stl_algo.h:208:17: error: invalid operands to binary expression ('Objectoid *' and 'const Objectoid')
if (*__first == __val)
sa.cc:27:19: note: in instantiation of function template specialization 'std::remove<__gnu_cxx::__normal_iterator<Objectoid **, std::vector<Objectoid *, std::allocator<Objectoid *> > >, Objectoid>' requested here
elements.erase(std::remove(elements.begin(), elements.end(), o), elements.end());
如果我把这行改成:
elements.erase(std::remove(elements.begin(), elements.end(), &o), elements.end());
然后一切都编译。我提供的版本是编译的,因为std::remove的第三个参数需要是你要迭代的对象的value_type
。您原来提供了一个Objectoid
,但我们需要它是您的容器的value_type
,这是一个Objectoid *
。
为了扩展第一个注意事项,一个好的简化问题陈述可以包括如下代码。它非常小,问题仍然很明显。任何人遇到这个问题,都能很快提供帮助。
#include <vector>
#include <algorithm>
class Objectoid {};
int main() {
std::vector<Objectoid *> elements;
Objectoid o;
elements.erase(std::remove(elements.begin(), elements.end(), o), elements.end());
}
你的问题没有意义,因为编译器在抱怨operator*
,但在你的例子中没有使用它。
contains
重写为:
bool contains(Objectoid &o) {
return std::find(elements.cbegin(), elements.cend(), &o) != elements.cend();
}
完全避免了这个问题
相关文章:
- 智能指针作为无序映射键,并通过引用进行比较
- std::less是否应该允许在编译时比较不相关的指针?
- 禁止指针和整数之间的比较C++
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 谷歌测试比较指针数组的内容
- 使用模板专用化来比较指针引用
- 重载 >= 运算符来比较指针
- 以C++(Arduino)为单位比较指针到字节
- 使用关系运算符比较指针意味着什么
- C++不会让我比较指针和整数
- 比较指针对象相等性
- 用于比较指针到 NULL 的编码标准
- 无法比较指针和整数c++
- 如何比较指针
- 在stl_algorithm .h中比较指针时出错
- ISO C++禁止在C++代码中比较指针和整数[-fpermissive]
- 比较指针和整数时出现编译器错误
- 标准::地图比较指针
- 比较指针.多重继承问题
- ISO c++禁止在devc++中比较指针和整数[-fpermissive]错误