【问题标题】:Why does my attempt to add to a vector within struct within a vector within a struct fail?为什么我尝试在结构内的向量内添加到结构内的向量失败?
【发布时间】:2017-01-02 21:25:25
【问题描述】:

我有这个问题有一段时间了,我想对此发表意见。如果您有更好的方法,请告诉我。 一切正常,除非我尝试访问它从不执行的实体中的项目的向量。总是说它是空的。

struct sObj{
    char itemName[64];
    int  itemStrenght;
};

struct sEnt{
    char entityName[64];
    vector<sObj> entityItems;
};

class cTemp{
public:
    void addEntity(sEnt entity){ entityList.push_back(sEnt); }
    void addItemToEnt(char* entityName, sObj itemDetails);
    void setAllItemStrenght(char* itemName, int newStr);
private:
    vector<sEnt> entityList;
};

void cTemp::addItemToEnt(char* entityName, sObj itemDetails){
    for(auto m : entityList){
        if(!_stricmp(m.entityName, entityName)){
            m.entityItems.push_back(itemDetails);
            m.entityItems.push_back(itemDetails); // just for testing
            msgBox("Item count: %i", m.entityItems.size()); // is working
        }
    }
}

void cTemp::setAllItemStrenght(char* itemName, int newStr){
    for(auto m : entityList){
        msgBox("Item count: %i", m.entityItems.size()); // returns 0
        for(auto n : m.entityItems){
            // never gets executed
        }
    }
}

【问题讨论】:

  • 在哪里打电话addItemToEnt?如果向量是空的,可能是因为你从不填充它。
  • 顺便说一下,你应该使用std::string
  • 我确实会相应地调用所有内容。上面发布的代码只是我的问题的一个例子。不是实际的代码,因为我想把它写成简短的帖子。弗兰克已经回答了确切的问题。还有@GuillaumeRacicot,可能。但是到目前为止,我编写所有内容的方式都是使用 char。它现在确实有效。我会接受你的建议并整合它。谢谢。

标签: c++ vector struct


【解决方案1】:

问题就在这里:

void cTemp::addItemToEnt(char* entityName, sObj itemDetails){
    for(auto m : entityList){

您的循环正在处理从entryList 复制的值,而不是对它们的引用。你想要:

for(auto& m : entityList){

【讨论】:

  • 非常感谢。我完全忽略了这一点。你刚刚为我节省了很多时间!我会尽快接受你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2017-04-26
  • 2021-12-26
相关资源
最近更新 更多