为什么我尝试在结构中的向量中添加到struct中的向量失败?

时间:2017-01-02 21:25:26

标签: c++ vector struct

我有一段时间有这个问题,我想就此发表意见。如果您有更好的方法,请告诉我。 一切都很好,除非我尝试访问它永远不会执行的实体内的项目的向量。总是说它是空的。

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

1 个答案:

答案 0 :(得分:5)

问题在于:

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

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

for(auto& m : entityList){