C++ vector::erase() 函数
vector::erase() 是 "vector" 头文件的库函数,用于从向量中擦除/删除元素,它可以从指定的迭代器位置删除一个元素或删除一系列元素。
注意:要使用矢量,请包括<vector>
标题。
vector::erase() 函数的语法
//remove one element vector::erase(iterator position); //remove a range of elements vector::erase(iterator start_position, iterator end_position);
参数:
如果删除一个元素:position
– 是一个迭代器位置,需要从中删除元素。
在删除一系列元素的情况下:start_position, end_position
– 是需要删除元素的开始和结束迭代器位置。
返回值: iterator
– 它返回一个迭代器,指向由 vector::erase() 函数擦除的最后一个元素后跟的元素。
例:
Input: vector<int> v1{10, 20, 30, 40, 50}; //removing one element v1.erase(v1.begin() + 2); //removes 2nd index element //removing a range of elements v1.erase(v1.begin() + 1, v1.begin() + 3); //removes 1,2 index elements Output: //if we print the values v1:10 50
C++程序演示vector::erase()函数的例子
//C++ STL program to demonstrate example of
//vector::erase() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector declaration
vector<int> v1{ 10, 20, 30, 40, 50 };
//printing elements
cout << "v1:";
for (int x:v1)
cout << x << " ";
cout << endl;
//removing one element
v1.erase(v1.begin() + 2); //removes 2nd index element
//printing elements after remove one element
cout << "After removing one element..." << endl;
cout << "v1:";
for (int x:v1)
cout << x << " ";
cout << endl;
//removing a range of elements
v1.erase(v1.begin() + 1, v1.begin() + 3); //removes 1,2 index elements
//printing elements after remove one element
cout << "After removing a range of elements..." << endl;
cout << "v1:";
for (int x:v1)
cout << x << " ";
cout << endl;
return 0;
}
输出
v1:10 20 30 40 50 After removing one element... v1:10 20 40 50 After removing a range of elements... v1:10 50
参考:C++ vector::erase()
相关用法
- C++ vector::emplace_back用法及代码示例
- C++ vector::empty()用法及代码示例
- C++ vector::empty()、vector::size()用法及代码示例
- C++ vector::end()用法及代码示例
- C++ vector::max_size()用法及代码示例
- C++ vector::rbegin()用法及代码示例
- C++ vector::pop_back()用法及代码示例
- C++ vector::crend()用法及代码示例
- C++ vector::push_back()用法及代码示例
- C++ vector::at()用法及代码示例
- C++ vector::swap()用法及代码示例
- C++ vector::shrink_to_fit()用法及代码示例
- C++ vector::cbegin()用法及代码示例
- C++ vector::back()用法及代码示例
- C++ vector::assign()用法及代码示例
- C++ vector::begin()用法及代码示例
- C++ vector::cend()用法及代码示例
- C++ vector::operator[]用法及代码示例
- C++ vector::clear()用法及代码示例
- C++ vector::cbegin()、vector::cend()用法及代码示例
注:本文由纯净天空筛选整理自 vector::erase() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。