stl_algo.h中的错误,比较指针

时间:2013-04-23 21:33:04

标签: c++ pointers compare

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

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'
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());
}

2 个答案:

答案 0 :(得分:1)

首先,评论:您现在提供了我们可以编译的内容,这很有帮助。话虽这么说,你提交的一堆代码不是问题的一部分(例如你的构造函数),我们实际上无法编译你提出的代码(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());
}

答案 1 :(得分:0)

您的问题没有意义,因为编译器抱怨operator*,但在您的示例中没有使用它。

同时,您应该使用STL算法并将contains重写为:

bool contains(Objectoid &o) {
    return std::find(elements.cbegin(), elements.cend(), &o) != elements.cend();
}

完全避免了这个问题。