1
只要您不刪除當前項目,在爲集合執行for_each時從集合中刪除元素是否合法?C++在for_each期間從擦除元素中刪除元素
設置擦除保持除正被擦除的所有迭代器都有效。
例如:
set<int> nums{0, 1, 2, 3, 4};
void weird_remove(int x) {
int randnum = rand() % 5;
if (randnum != x) {
nums.erase(randnum);
}
}
int main() {
for_each(nums.begin(), nums.end(), weird_remove);
}
而且怎麼樣範圍在循環中?
我假設答案適用於地圖以及設置。