Как удалить элемент из вектора c
Prerequisite: Vector 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
- It has a no exception throw guarantee.
- 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
- It has no exception throw guarantee if the position is valid.
- 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
- Run a loop to the size of the vector.
- Check if the element at each position is divisible by 2, if yes, remove the element and decrement the iterator.
- 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.
Как удалить элемент из вектора c
Для добавления элементов в вектор применяется функция push_back() , в которую передается добавляемый элемент:
Векторы являются динамическими структурами в отличие от массивов, где мы скованы его заданым размером. Поэтому мы можем динамически добавлять в вектор новые данные.
Функция emplace_back() выполняет аналогичную задачу — добавляет элемент в конец контейнера:
Добавление элементов на определенную позицию
Ряд функций позволяет добавлять элементы на определенную позицию.
emplace(pos, value) : вставляет элемент value на позицию, на которую указывает итератор pos
insert(pos, value) : вставляет элемент value на позицию, на которую указывает итератор pos, аналогично функции emplace
insert(pos, n, value) : вставляет n элементов value начиная с позиции, на которую указывает итератор pos
insert(pos, begin, end) : вставляет начиная с позиции, на которую указывает итератор pos, элементы из другого контейнера из диапазона между итераторами begin и end
insert(pos, values) : вставляет список значений начиная с позиции, на которую указывает итератор pos
Удаление элементов
Если необходимо удалить все элементы вектора, то можно использовать функцию clear :
Функция pop_back() удаляет последний элемент вектора:
Если нужно удалить элемент из середины или начала контейнера, применяется функция std::erase() , которая имеет следующие формы:
erase(p) : удаляет элемент, на который указывает итератор p. Возвращает итератор на элемент, следующий после удаленного, или на конец контейнера, если удален последний элемент
erase(begin, end) : удаляет элементы из диапазона, на начало и конец которого указывают итераторы begin и end. Возвращает итератор на элемент, следующий после последнего удаленного, или на конец контейнера, если удален последний элемент
Также начиная со стандарта С++20 в язык была добавлена функция std::erase() . Она не является частью типа vector. В качестве первого параметра она принимает вектор, а в качестве второго — элемент, который надо удалить:
В данном случае удаляем из вектора numbers3 все вхождения числа 1.
Размер вектора
С помощью функции size() можно узнать размер вектора, а с помощью функции empty() проверить, путой ли вектор:
С помощью функции resize() можно изменить размер вектора. Эта функция имеет две формы:
resize(n) : оставляет в векторе n первых элементов. Если вектор содержит больше элементов, то его размер усекается до n элементов. Если размер вектора меньше n, то добавляются недостающие элементы и инициализируются значением по умолчанию
resize(n, value) : также оставляет в векторе n первых элементов. Если размер вектора меньше n, то добавляются недостающие элементы со значением value
Важно учитывать, что применение функции resize может сделать некорректными все итераторы, указатели и ссылки на элементы.
Изменение элементов вектора
Функция assign() позволяет заменить все элементы вектора определенным набором:
В данном случае элементы вектора заменяются набором из четырех строк «C++».
Также можно передать непосредственно набор значений, который заменит значения вектора:
Еще одна функция — swap() обменивает значения двух контейнеров:
Сравнение векторов
Векторы можно сравнивать — они поддерживают все операции сравнения: <, >, <=, >=, ==, !=. Сравнение контейнеров осуществляется на основании сравнения пар элементов на тех же позициях. Векторы равны, если они содержат одинаковые элементы на тех же позициях. Иначе они не равны:
Remove an element from a vector by value — C++
Where each element in the list is unique, what’s the easiest way of deleting an element provided that I don’t know if it’s in the list or not? I don’t know the index of the element and I don’t care if it’s not on the list.
4 Answers 4
Or, if you’re sure, that it is unique, just iterate through the vector and erase the found element. Something like:
Based on Kiril’s answer, you can use this function in your code :
And use it like this
If occurrences are unique, then you should be using std::set<T> , not std::vector<T> .
This has the added benefit of an erase member function, which does what you want.
See how using the correct container for the job provides you with more expressive tools?
C++ std::vector Deleting Elements
Note: For a vector deleting an element which is not the last element, all elements beyond the deleted element have to be copied or moved to fill the gap, see the note below and std::list.
Deleting all elements in a range:
Note: The above methods do not change the capacity of the vector, only the size. See Vector Size and Capacity.
The erase method, which removes a range of elements, is often used as a part of the erase-remove idiom. That is, first std::remove moves some elements to the end of the vector, and then erase chops them off. This is a relatively inefficient operation for any indices less than the last index of the vector because all elements after the erased segments must be relocated to new positions. For speed critical applications that require efficient removal of arbitrary elements in a container, see std::list.
Deleting elements by value:
Deleting elements by condition:
Deleting elements by lambda, without creating additional predicate function
Deleting elements by condition from a loop:
While it is important not to increment it in case of a deletion, you should consider using a different method when then erasing repeatedly in a loop. Consider remove_if for a more efficient way.
Deleting elements by condition from a reverse loop:
Note some points for the preceding loop:
Given a reverse iterator it pointing to some element, the method base gives the regular (non-reverse) iterator pointing to the same element.
vector::erase(iterator) erases the element pointed to by an iterator, and returns an iterator to the element that followed the given element.
reverse_iterator::reverse_iterator(iterator) constructs a reverse iterator from an iterator.
Put altogether, the line it = rev_itr(v.erase(it.base())) says: take the reverse iterator it , have v erase the element pointed by its regular iterator; take the resulting iterator, construct a reverse iterator from it, and assign it to the reverse iterator it .
Deleting all elements using v.clear() does not free up memory ( capacity() of the vector remains unchanged). To reclaim space, use:
shrink_to_fit() frees up unused vector capacity:
The shrink_to_fit does not guarantee to really reclaim space, but most current implementations do.