int main()
{
const int SIZE = 10;
int a[SIZE] = {10, 2, 35, 5, 10, 26, 67, 2, 5, 10};
std::ostream_iterator< int > output(cout, " ");
std::vector< int > v(a, a + SIZE);
std::vector< int >::iterator newLastElement;
cout << "contents of the vector: ";
std::copy(v.begin(), v.end(), output);
newLastElement = std::remove(v.begin(), v.end(), 10);
cout << "\ncontents of the vector after remove: ";
//std::copy(v.begin(), newLastElement, output);
//this gives the correct result : 2 35 5 26 67 2 5
std::copy(v.begin(), v.end(), …Run Code Online (Sandbox Code Playgroud) 迭代器擦除(迭代器位置);
迭代器擦除(迭代器优先,迭代器最后);
擦除元素从向量容器中移除单个元素(位置)或一系列元素([first,last)).
这有效地减少了矢量大小,删除了元素的数量,之前调用每个元素的析构函数.
和:
去掉
从[first,last]定义的范围中移除所有等于给定值的元素.通过移动范围中的元素以便覆盖所需元素来完成移除.范围的旧端和新端之间的元素保持不变.返回到范围的新结尾的迭代器.
有没有办法从迭代器范围内的std :: vector中删除元素(类似于remove,但是[first,last]中的所有元素)而不调整向量的大小?我需要保持它在运行时达到的最大大小以防止重新分配.
谢谢!