Перейти к содержимому

Как удалить элемент из вектора c

  • автор:

std:: vector::erase

Removes from the vector either a single element (position) or a range of elements ([first,last)).

This effectively reduces the container size by the number of elements removed, which are destroyed.

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

Parameters

Return value

An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

Member type iterator is a random access iterator type that points to elements.

Different ways to remove elements from vector in C++ STL

Learn Algorithms and become a National Programmer

In this article, we will go through multiple ways to delete elements from a vector container in C++ Standard Template Library (STL). Methods used to remove elements from vector are:

  • vector::pop_back()
  • vector::pop_front()
  • vector::erase()
  • vector::clear()
  • remove(first,last,val)
  • remove_if()
  • remove_copy(first,last,result,val)

Before going into it, we will go through a quick review of vector basics.

Vectors are same as dynamic arrays with the ability to resize itself automatically while insertion and deletion. Vectors are placed in contiguous storage so that they can be accessed and traversed using iterators.

Defining a vector:

vector::push_back() is used to insert elements into a vector.Insertion happens at the end.

Insertion at the end takes linear time, as sometimes there may be a need of extending the array.
Removing the last element takes constant time because no resizing happens.
Inserting or removing element in the middle is linear in time.

Functions to be known:

  1. vector.size() Returns the number of elements in vector.
  2. vector.begin() Returns an iterator pointing to the first element in vector.
  3. vector.end() Returns an iterator pointing to the theoretical element that follows the last element in the vector.
  4. vector.push_back(val) Push element (val) into the vector from back.
  5. vector.empty() Returns whether vector is empty.

We will now get started with the different methods to remove elements from a vector.

vector::pop_back()

vector::pop_back() method is used to remove elements stored inside a vector.
It reduces the container size by one and destroys the removed element.

Syntax:

  • Parameters: None
  • Return value: None

Errors and Exceptions:
1.No-Throw-Guarantee: If an exception is thrown, there is no change in the container.
2.If vector is empty, it shows undefined behavior.

Does pop_back() removes values along with elements?
When this function is called, element at the last is removed. The destructor of the object is called and length of vector is decreased by 1.

Time Complexity: O(1) or (constant)

vector::pop_front()

This is similar to pop_back() but removes elements from the front instead of back.

Syntax:

vector::erase()

Removes either a single element or a range of elements.

Syntax:

Parameters: Position of the element or range of elements to be removed.
Result: Elements are removed from the position specified.
Time Complexity: O(N) — worst case, O(1) — best case

vector::clear()

This method removes all elements from container, leaving with size 0.

Syntax:

Parameters: No Parameters
Return: All elements of the vector are destroyed
Time Complexity: O(N)

Difference between clear() and erase():
clear() removes all elements from vector and reducing it to size 0.
erase() is used to remove specific elements from vector.

remove(first,last,val)

This method removes all elements which are equal to val and returns an iterator to the new end of that range.
Syntax:

Parameters:

  • first,last: The range is used which contains all elements between first and last includeing first but not last.
  • val: Value to be removed.

Result: An iterator to the element that follows the last element not removed.

Difference between remove() and erase()?

erase() causes large amount of copies while remove() just does a logical delete and leaves vector unchanged by moving element around.

If you need to remove multiple elements, remove() will copy elements only once to its final position while erase() would do this multiple times.

erase() works best with elements in a position, remove() is best while working with range of elements.

remove_if()

Transforms the range [first,last) into a range with all elements for which func returns true removed.

Syntax:

Parameters:
ForwardIterator first,last
UnaryPredicate func: This function accepts an element in the range as argument, and returns a value convertible to bool. If true, remove element.

remove_copy(first,last,result,val)

Copies the elements in the range of vector to another vector except those that equal the value specified.

Syntax:

Parameters:

ForwardIterator first, last:
OutputIterator result
val: The value that needs to be removed.

With this, you have the complete knowledge of different ways to remove elements from C++ STL vector container.

vector erase() and clear() in C++

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

vector::clear()

The clear() function is used to remove all the elements of the vector container, thus making it size 0.

Syntax:

Parameters: No parameters are passed.

Result: All the elements of the vector are removed (or destroyed).

Example:

Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
All elements are destroyed one by one.

Errors and Exceptions

  1. It has a no exception throw guarantee.
  2. It shows an error when a parameter is passed.

vector::erase()

erase() function is used to remove elements from a container from the specified position or range.

Syntax:

Parameters:

  • Position of the element to be removed in the form of an iterator.
  • The range specified using start and end iterators.

Result: Elements are removed from the specified position of the container.

Example:

Removing an element from a particular position

Example:

Time Complexity: O(N)
Auxiliary Space: O(1)

Removing elements within a range

Example:

Time Complexity: O(N)
Auxiliary Space: O(1)

Removing vector pair elements

Example:

Time Complexity: O(N)
Auxiliary Space: O(1)

Errors and Exceptions

  1. It has no exception throw guarantee if the position is valid.
  2. Shows undefined behavior otherwise.

Application

Given a list of integers, remove all the even elements from the vector and print the vector.

Input:

Output:

Explanation: 2, 4, 6, and 8 which are even and erased from the vector

Algorithm
  1. Run a loop to the size of the vector.
  2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement the iterator.
  3. Print the final vector.

The below program implements the above approach.

Time Complexity: O(N) in the worst case as an erase takes linear time.

clear() vs erase(), When to use what?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using the clear() function.

erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

How do I erase an element from std::vector<> by index?

I have a std::vector<int> , and I want to delete the n th element. How do I do that?

W D's user avatar

16 Answers 16

To delete a single element, you could do:

Or, to delete more than one element at once:

The erase method on std::vector is overloaded, so it’s probably clearer to call

when you only want to erase a single element.

Benjamin Buch's user avatar

The erase method will be used in two ways:

Erasing single element:

Erasing range of elements:

Erase an element with index :

Erase an element with value:

Actually, the erase function works for two profiles:

Removing a single element

Removing a range of elements

Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use:

If you look closely, vec.begin() is just a pointer to the starting position of our vector and adding the value of i to it increments the pointer to the position i . So, we instead can access the pointer to the i th element with &vec[i] :

Benjamin Buch's user avatar

Varun Garg's user avatar

If you have an unordered vector you can take advantage of the fact that it’s unordered and use something I saw from Dan Higgins at CPPCON

Since the list order doesn’t matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.

Clay J's user avatar

It may seem obvious to some people, but to elaborate on the above answers:

If you are doing removal of std::vector elements using erase in a loop over the whole vector, you should process your vector in reverse order, that is to say using

for (int i = v.size() — 1; i >= 0; i—)

instead of (the classical)

for (int i = 0; i < v.size(); i++)

The reason is that indices are affected by erase so if you remove the 4-th element, then the former 5-th element is now the new 4-th element, and it won’t be processed by your loop if you’re doing i++ .

Below is a simple example illustrating this where I want to remove all the odds element of an int vector;

Note that on the second version with increasing indices, even numbers are not displayed as they are skipped because of i++

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *