为什么循环此向量时会出现分段错误?

问题描述 投票:0回答:1

当我运行此代码时,出现分段错误。我正在使用 C++ 14 和 Clion。看起来它在第六或第七循环时崩溃了。看起来它来自我从向量中删除元素的地方。如果有更好的方法来迭代向量,请告诉我,我仍在尝试学习用 C++ 编写代码。

#include <vector>
#include <synchapi.h>

class someClass{
public:
    int x;
    int y;
    int health = 0;
    someClass(int a, int b){
        x = a;
        y = b;
    }
};

std::vector<someClass> classList;

int main() {

    for (int i = 0; i < 7; ++i) {
        someClass newclass(i, i*3);
        classList.push_back(newclass);
    }

    while(true) {
        int iter = 0;
        if(!classList.empty()) {
            for (auto &e: classList) {

                if (e.health == 0) {
                    classList.erase(classList.begin() + iter); 
                    if(iter != 0){
                        iter--;
                    }
                }
                iter++;
            }
        }
        Sleep(50);
    }
    return 0;
}
c++ vector segmentation-fault c++14
1个回答
0
投票

当您修改集合并迭代它时,往往会发生不好的事情。

如果需要修改原始集合,请使用

remove-erase idiom

std::erase( std::remove_if( classList.begin(), classList.end(), [](auto &x){ return x.health == 0; } ), classList.end() );
    
© www.soinside.com 2019 - 2024. All rights reserved.