且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从stl向量中删除具有某个值的项目?

更新时间:2023-01-17 17:44:46

std :: remove实际上不会从容器中擦除元素,但它会返回新的结束迭代器,它可以传递给container_type :: erase来删除现在位于容器末尾的额外元素:

std::remove doesn't actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());