You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++嵌套vector<float>及引用操作:幽灵数组遍历更新问题排查

最终解决方案

最后更新:我找到解决方法了!

//使用指针初始化每个集合
array<float, 3> monster1 = { 10.5, 8.5, 1.0 }; //第一个怪物的坐标和朝向
array<float, 3> monster2 = { 13.5, 1.5, 2.0 }; //第二个怪物的坐标和朝向
array<float, 3> monster3 = { 4.5, 6.5, 3.0 }; //第三个怪物的坐标和朝向
array<float, 3> monster4 = { 2.5, 13.5, 4.0 }; //第四个怪物的坐标和朝向

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 };

...

//函数定义
void updateMonster(array<float, 3>& monster);

...

//适配的for循环与函数调用
void display() {
    if (!over) {
        for (auto list : all_ghosts) {
            for (auto ghost : *list) {
                updateMonster(*ghost);
            }
        }
    }
}

原始问题

我正在修改一个C++吃豆人项目,项目中幽灵的定义为float数组:

float* monster1 = new float[3]{ 10.5, 8.5, 1.0 }; //第一个怪物的坐标和朝向
...
float* monster4 = new float[3]{ 2.5, 13.5, 4.0 }; //第四个怪物的坐标和朝向

目前通过如下函数逐个更新怪物的逻辑可以正常运行:

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循环遍历的方式始终无法正常工作,请问我的引用/指针哪里存在错误?谢谢!

补充说明

我需要怪物集合支持动态增减,因此需要使用vector。但我按如下方式声明后:

float* monster1 = new float[3]{ 10.5, 8.5, 1.0 }; //第一个怪物的坐标和朝向
...
static vector<float*> v = { monster1, monster2, monster3, monster4 };

使用如下方式遍历时没有得到预期效果:

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

内容的提问来源于stack exchange,提问作者it's jayway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:51:04