YouTip LogoYouTip

Cpp Libs Vector Erase

[![Image 1: C++ Container Class ](#) C++ Container Class ](#)\\n\\n* * *\\n\\n`erase` is a function in vector used to **delete elements at a specified position**, and it is the most flexible way to delete in the container.\\n\\n`erase` is a member function of the container class, used to **delete one or more elements at specified positions in the container**. It accepts iterator parameters.\\n\\n`erase` provides the ability to delete elements at any position. Although it is less efficient than `pop_back` in a vector (because it requires moving subsequent elements), it is more powerful.\\n\\n**Word Definition**: `erase` means "to erase", i.e., to delete the element at the specified position.\\n\\n* * *\\n\\n## Basic Syntax and Parameters\\n\\n`erase` is a member function of the container class, and requires an iterator specifying the position to delete.\\n\\n### Syntax Format\\n\\n// Delete pos Element at position: iterator erase(iterator pos);// Delete [first, last) All elements in the range: iterator erase(iterator first, iterator last);\\n### Parameter Description\\n\\n* **Parameter**: `pos`\\n * Type: Iterator (`iterator`)\\n * Description: The position of the element to be deleted.\\n\\n * **Parameter**: `first`, `last`\\n * Type: Iterator (`iterator`)\\n * Description: The starting and ending iterators of the range of elements to be deleted. The deletion range is [`first`, `last`), meaning it includes `first` but does not include `last`.\\n\\n### Function Description\\n\\n * **Return Value**: Returns an iterator pointing to the position following the last deleted element (i.e., the element originally at the `last` position).\\n * **Effect**: Deletes the element at the specified position, and subsequent elements move forward in turn.\\n * **Note**: After `erase` deletes an element, the following elements will move forward, and iterators may become invalid.\\n\\n* * *\\n\\n## Examples\\n\\nLet's thoroughly master the usage of `erase` through a series of examples.\\n\\n### Example 1: Basic Usage - Deleting a Single Element\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\nint main(){\\n\\n std::vector numbers ={1, 2, 3, 4, 5};\\n\\nstd::cout<<"Original vector: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\n// DeleteElement at the second position (index 1)\\n\\nauto it = numbers.begin()+1;\\n\\n numbers.erase(it);\\n\\nstd::cout<<"DeletePost: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\nreturn 0;\\n\\n}\\n\\n**Expected Output:**\\n\\nOriginal vector: 1 2 3 4 5DeletePost: 1 3 4 5\\n**Code Analysis:**\\n\\n 1. `numbers.begin() + 1` points to the second element (value 2).\\n 2. `erase` deletes the element at this position.\\n 3. Subsequent elements (3, 4, 5) all move forward by one position.\\n\\n### Example 2: Deleting Elements at the Beginning and End\\n\\nUsing `begin()` and `end()`, you can delete elements at the beginning and the end.\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\nint main(){\\n\\n std::vector numbers ={10, 20, 30, 40, 50};\\n\\nstd::cout<<"Original: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\n// DeleteFirst element\\n\\n numbers.erase(numbers.begin());\\n\\n std::cout<<"DeleteFirst elementPost: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\n// DeleteLast element (end() points after the last element)\\n\\n numbers.erase(numbers.end()-1);\\n\\n std::cout<<"DeleteLast element: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\nreturn 0;\\n\\n}\\n\\n**Expected Output:**\\n\\nOriginal: 10 20 30 40 50DeleteFirst elementPost: 20 30 40 50DeleteLast element: 20 30 40\\n**Code Analysis:**\\n\\n * `erase(begin())` deletes the first element.\\n * `erase(end() - 1)` deletes the last element (note that `end()` points past the last element).\\n\\n### Example 3: Deleting Multiple Elements (Range)\\n\\nYou can delete all elements within a specified range.\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\nint main(){\\n\\n std::vector numbers ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\\n\\nstd::cout<<"Original: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\n// DeleteElements from second to fifth (index 1 to 4)\\n\\nauto first = numbers.begin()+1;\\n\\nauto last = numbers.begin()+5;\\n\\n numbers.erase(first, last);\\n\\nstd::cout<<"DeletePosition [1, 5) Post: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\nreturn 0;\\n\\n}\\n\\n**Expected Output:**\\n\\nOriginal: 1 2 3 4 5 6 7 8 9 10DeletePosition [1, 5) Post: 1 6 7 8 9 10\\n**Code Analysis:**\\n\\n * `erase(first, last)` deletes all elements from `first` up to (but not including) `last`.\\n * Here, it deleted the elements at indices 1, 2, 3, and 4 (values 2, 3, 4, 5).\\n\\n### Example 4: Deleting All Odd Numbers\\n\\nCombined with a loop, you can delete elements that meet a condition.\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\nint main(){\\n\\n std::vector numbers ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\\n\\nstd::cout<<"Original: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\n// DeleteAll odd numbers\\n\\nfor(auto it = numbers.begin(); it != numbers.end();){\\n\\nif(*it %2==1){// If odd\\n\\n it = numbers.erase(it);// erase Returns an iterator to the next element\\n\\n}else{\\n\\n++it;\\n\\n}\\n\\n}\\n\\nstd::cout<<"DeleteFirst element: ";\\n\\nfor(int n : numbers) std::cout<< n <<" ";\\n\\n std::cout<< std::endl;\\n\\nreturn 0;\\n\\n}\\n\\n**Expected Output:**\\n\\nOriginal: 1 2 3 4 5 6 7 8 9 10DeleteFirst element: 2 4 6 8 10\\n**Code Analysis:**\\n\\n * When deleting elements in a loop, be careful to update the iterator.\\n * `erase` returns an iterator pointing to the next element; this is the correct way to delete.\\n\\n### Example 5: Efficiency Issues with erase\\n\\nDeleting middle elements in a vector using `erase` is less efficient.\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\n#include \\n\\nint main(){\\n\\nconst int N =10000;\\n\\n// DeleteFirst element (low efficiency)\\n\\n std::vector v1;\\n\\nfor(int i =0; i < N;++i) v1.push_back(i);\\n\\nauto start1 = std::chrono::high_resolution_clock::now();\\n\\nwhile(!v1.empty()){\\n\\n v1.erase(v1.begin());\\n\\n}\\n\\nauto end1 = std::chrono::high_resolution_clock::now();\\n\\nauto duration1 = std::chrono::duration_cast(end1 - start1);\\n\\n// DeleteLast element (high efficiency)\\n\\n std::vector v2;\\n\\nfor(int i =0; i < N;++i) v2.push_back(i);\\n\\nauto start2 = std::chrono::high_resolution_clock::now();\\n\\nwhile(!v2.empty()){\\n\\n v2.pop_back();\\n\\n}\\n\\nauto end2 = std::chrono::high_resolution_clock::now();\\n\\nauto duration2 = std::chrono::duration_cast(end2 - start2);\\n\\nstd::cout<<"Delete from the beginning "<< N <<" Time taken for elements: "<< duration1.count()<<" Microseconds"<< std::endl;\\n\\n std::cout<<"Delete from the end "<< N <<" Time taken for elements: "<< duration2.count()<<" Microseconds"<< std::endl;\\n\\nreturn 0;\\n\\n}\\n\\n**Code Analysis:**\\n\\n * Deleting elements from the beginning of a vector requires moving all subsequent elements, which is very inefficient.\\n * Deleting elements from the end (`pop_back`) does not require moving elements, making it highly efficient.\\n * If you need to frequently delete elements from the beginning, consider using `deque` or `list`.\\n\\n### Example 6: Using erase for Data Filtering\\n\\n`erase` can be used to filter data.\\n\\n## Instance\\n\\n#include \\n\\n#include \\n\\n#include \\n\\n// Simple failing grade filter\\n\\nvoid filterFailing(std::vector& scores){\\n\\nfor(auto it = scores.begin(); it != scores.end();){\\n\\nif(*it <60){\\n\\n it = scores.erase(it);\\n\\n}else{\\n\\n++it;\\n\\n}\\n\\n}\\n\\n}\\n\\nint main(){\\n\\n std::vector scores ={85, 92, 45, 78, 55, 90, 67};
← Cpp Libs Array AtCpp Libs Vector Clear β†’