简体   繁体   English

C ++使用std :: vector迭代类指针

[英]C++ Iteration over class pointers using std::vector

I am trying to Iterate over a vector using pointers I have a vector called: 我试图使用指针迭代一个向量我有一个名为的向量:

 std::vector<GameObject*> objects;

and a load of functions like these: 和这些函数的负载:

void Game::update()
 {
    std::vector<GameObject*>::iterator itr;
    for( itr = objects.begin();itr < objects.end();++itr)
    {
        itr->update();//I need to call a abstract function in the GameObject Class
    }
 }
 Game::~Game()
 {

    delete ball;
    delete player;
 }
Game::Game()
{
    ball = new GOBall(800/2 - GOBall::SIZE/2,600/2 - GOBall::SIZE/2);
    player = new GOPlayer(0, 600/2 - GOPlayer::SIZEY/2,ball);
    objects.push_back(ball);
    objects.push_back(player);
}

As you can see I am trying to iterate in a way that still allows me to call the function and also parse the polymorphistic class into other polymorphistic classes(hence the reason its declared before being parsed into the vector), what I keep getting is error: 正如你所看到的那样,我试图以一种方式进行迭代,这种方式仍然允许我调用函数并将多态类解析为其他多态类(因此它在被解析为向量之前声明它的原因),我一直得到的是错误:

C2839: invalid return type 'GameObject *const *' for overloaded 'operator ->' C2839:重载'运算符 - >'的返回类型'GameObject * const *'无效

and error: 和错误:

C2039: 'update' : is not a member of 'std::_Vector_const_iterator<_Ty,_Alloc>' C2039:'update':不是'std :: _ Vector_const_iterator <_Ty,_Alloc>'的成员

which tells me i cant call ball->update() or player->update() through the iterator, so how do I do it? 告诉我我不能通过迭代器调用ball->update()player->update() ,所以我该怎么做?

In C++11: 在C ++ 11中:

for (GameObject* gameObject : objects) {
    gameObject->update();
}

You need to dereference the iterator 您需要取消引用迭代器

(*itr)->update();

This is the short way to say: 这是简短的说法:

GameObject* pGameObject = *itr;
pGameObject->update();

We can use range-based for loop one step better: 我们可以更好地使用基于范围的for循环:

for (auto& game_object : objects)
  game_object->update();

The more complex way is to create your own custom iterator adaptor. 更复杂的方法是创建自己的自定义迭代器适配器。 Here's an example (complete example will compile and run): 这是一个例子(完整的例子将编译并运行):

#include <iostream>

#include <vector>
#include <memory>

struct GameObject {
    GameObject(int id)
    : _id { id }
    {}

    virtual void fireLazorz() {
        std::cout << "Game Object " << _id
        << ": I'm a-firin' mah lazorz!" << std::endl;
    }
private:
    int _id;
};


using vec_t = std::vector<std::unique_ptr<GameObject>>;

struct gameobject_deref_iterator : public vec_t::const_iterator
{
    using parent_t = vec_t::const_iterator;

    gameobject_deref_iterator(parent_t src)
    : parent_t(std::move(src))
    {

    }

    // override the indirection operator
    GameObject& operator*() const {
        return *(parent_t::operator*());
    }

    GameObject* operator->() const {
        return parent_t::operator->()->get();
    }

};
using namespace std;

int main()
{
    vec_t gameObjects;

    for(int i = 0 ; i < 10 ; ++i) {
        gameObjects.emplace_back(
                                 new GameObject{ i }
                                 );
    }

    // now iterate the game objects, starting with the 5th one

    gameobject_deref_iterator first { next(begin(gameObjects), 5) };
    gameobject_deref_iterator last { end(gameObjects) };
    cout << "We have " << last - first << " GameObjects:" << endl;
    for(auto it = first ; it != last ; ++it) {
        it->fireLazorz();
    }

    return 0;
}

output: 输出:

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
We have 5 GameObjects:
Game Object 5: I'm a firin my lazorz!
Game Object 6: I'm a firin my lazorz!
Game Object 7: I'm a firin my lazorz!
Game Object 8: I'm a firin my lazorz!
Game Object 9: I'm a firin my lazorz!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM