1: c.erase(remove(c.begin(), c.end(), 1963), c.end()); // c is continguous memory container 2: c.remove(1963); // c is list 3: c.erase(1963) // c is standard associative container
对于 continguous memory container 来讲, std::remove() 能够保证返回的 iterator 以前的内存中不包含被删除的值,配合 erase 来用,造成所谓的 erase-remove idiom 。而对于 List 来讲,应该调用 list 自己的 remove() 方法。对于 map,set 等等,则必须使用 erase() 方法,而不能使用 remove() ,对 associative container 使用 remove() 可能会覆盖容器存储的内容,甚至破坏容器。c++
假设咱们如今想给定一个条件( bool badValue(int x) )并用这个条件来判断有哪些 Entry 须要删除,对 vector、string、deque、list 能够用下列方法:sql
1: c.erase(remove_if(c.begin(), c.end(), badValue), c.end()); // for vector, string, deque ... 2: c.remove_if(badValue); // for list.
associative container 没有相似的方法,但能够自行遍历删除:bash
AssocContainer<int> c; for (AssocContainer<int>::iterator i=c.begin(); i != c.end(); ++i) { if (badValue(*i)) { c.erase(i); //XXX: This is wrong: when this get executed, iterator will become //XXX: invalid, and ++i will lead to undefined behaviour. } } for (AssocContainer<int>::iterator i=c.begin(); i != c.end(); /*Nothing*/) { if (badValue(*i)) { c.erase(i++); //XXX: This works, because we are passing unincreased value to erase, //XXX: but we get it increased before it was passed to erase(). } else { i++; } }