在stl_algorithm .h中比较指针时出错

Error in stl_algo.h, comparing pointers

本文关键字:比较 指针 出错 stl algorithm      更新时间:2023-10-16

我试图找出对象是否存在于指针向量中。

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*,但在你的例子中没有使用它。

同时,您应该使用STL算法并将contains重写为:
bool contains(Objectoid &o) {
    return std::find(elements.cbegin(), elements.cend(), &o) != elements.cend();
}

完全避免了这个问题