#include<vector> int main(){ std::vector<int> v; v.push_back(100); v.push_back(101); for(std::vector<int>::iterator ite=v.begin(), end=v.end(); ite!=end;){ if(*ite%2){ ite=v.erase(ite); }else{ ++ite; } } return 0; }
vectorで要素のerase()を行う上記コードを実行すると、
vector iterators incompatible
と怒られてしまいます。
原因は、erase()したにもかかわらず、初期化で代入した変数endを使用していることにあります。
end=v.end(); ite!=end;){
無駄な関数呼び出しをしないためによく用いられる手法ですが、
自分のような初心者が何も考えずにコピペすると陥る罠ですね。
広告


広告