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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。