標準で明示的にコンテナの変更をstd::for_each
以内に禁止していますか?std :: for_each内のコンテナを変更する
具体的には、std::list
の場合、リストが変更されるとイテレータは無効になりません。したがって、次のコードが動作します。
std::list<int> list;
list.push_front(5);
list.push_front(10);
auto it = list.end();
it--; // point to 5
std::for_each(list.begin(), list.end(), [&](int i){
/* the line below will remove the last element in the list;
* list will have only one element (the currently processed one);
* list.end() is not invalidated and we exit for_each() */
list.erase(it);
});
これは間違いなく悪いコードです。しかしそれは合法ですか?
この質問は、もっともっと上げられるはずです。本当に... –