嵌套向量<float> 和引用操作

Nested vector<float> and reference manipulation

最终编辑:我明白了!

//Initialize each collection using pointers

array<float, 3> monster1 = { 10.5, 8.5, 1.0 }; //coordinates and direction of first monster
array<float, 3> monster2 = { 13.5, 1.5, 2.0 }; //coordinates and direction of second monster
array<float, 3> monster3 = { 4.5, 6.5, 3.0 }; //coordinates and direction of third monster
array<float, 3> monster4 = { 2.5, 13.5, 4.0 }; //coordinates and direction of fourth monster

vector<array<float,3>*> pinkys = { &monster1 };
vector<array<float, 3>*> blinkys = { &monster2 };
vector<array<float, 3>*> inkys = { &monster3 };
vector<array<float, 3>*> clydes = { &monster4 };

vector<vector<array<float,3>*>*> all_ghosts = { &pinkys, &blinkys, &inkys, &clydes };

...

//Function definition

void updateMonster(array<float, 3>& monster);

...

//appropriate for loop and function call

void display() {
    if (!over) {
            
        for (auto list : all_ghosts) {
            for (auto ghost : *list) {
                updateMonster(*ghost);
            }
            }
}

下面的原始问题

我正在尝试修改 C++ pacman project,其中幽灵被定义为浮点数组:

float* monster1 = new float[3]{ 10.5, 8.5, 1.0 }; //coordinates and direction of first monster
...
float* monster4 = new float[3]{ 2.5, 13.5, 4.0 }; //coordinates and direction of fourth monster

目前,它们正在通过函数逐个成功更新:

void updateMonster(float* monster) { ... }

这叫做:

void display() {
    ...
        if (!over) {
            
            updateMonster(monster1);
            updateMonster(monster2);
            updateMonster(monster3);
            updateMonster(monster4);
            
        }
    ...
}

我的目标是将原始怪物添加到 vector<float*> 中,以便我可以在 for 循环中遍历它们并更新它们:

static vector<float*> v = { monster1, monster2, monster3, monster4 };
...

void display() {
    ...
        if (!over) {
            
            for (auto* m : v) {
                updateMonster(m);
            }
            
        }
    ...
}

但是,它在for循环中并没有成功。我的 references/pointers 哪里出错了?谢谢!

编辑: 我应该提到我想让我的怪物集合变大和变小,因此需要一个向量。但我的问题是,当我这样声明它们时:

float* monster1 = new float[3]{ 10.5, 8.5, 1.0 }; //coordinates and direction of first monster
...
static vector<float*> v = { monster1, monster2, monster3, monster4 };

当我遍历它们时,它没有像我预期的那样工作:

for (auto& m : v) {
                updateMonster(m);
            }

(my progress)

您可以使用 std::array。无需使用原始指针:

#include <array>
#include <vector>

using Monster = std::array<float, 3>;

void updateMonster(Monster& monster);

int main() {
  std::vector<Monster> monsters;

  monsters.push_back(Monster{1.f, 2.f, 3.f});
  monsters.push_back(Monster{4.f, 5.f, 6.f});
  monsters.push_back(Monster{7.f, 8.f, 9.f});

  for (auto& monster : monsters) updateMonster(monster);
}

Godbolt