Remove an element from a vector

remove element from vector c++ by value
remove last element from vector c++
c++ remove element from vector while iterating
find element in vector c++
removing vector element by index
delete ith element of vector
delete all elements of a vector
vector remove a specific element

Is there a simple way to remove an element from a Vec<T>?

There's a method called remove(), and it takes an index: usize, but there isn't even an index_of() method that I can see.

I'm looking for something (hopefully) simple and O(n).


This is what I have come up so far (that also makes the borrow checker happy):

let index = xs.iter().position(|x| *x == some_x).unwrap();
xs.remove(index);

I'm still waiting to find a better way to do this as this is pretty ugly.

Note: my code assumes the element does exist (hence the .unwrap()).

vector::erase - C++ Reference, All the elements of the vector are removed using clear() function. erase() function on the other hand, is used to remove specific elements from the container or a  vector::erase () 1. Run a loop till the size of the vector. 2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement iterator. 3. Print the final vector.


You can use the retain method but it will delete every instance of the value:

fn main() {
    let mut xs = vec![1, 2, 3];
    let some_x = 2;
    xs.retain(|&x| x != some_x);
    println!("{:?}", xs); // prints [1, 3]
}

vector erase() and clear() in C++, If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the 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.


Your question is under-specified: do you want to return all items equal to your needle or just one? If one, the first or the last? And what if there is no single element equal to your needle? And can it be removed with the fast swap_remove or do you need the slower remove? To force programmers to think about those questions, there is no simple method to "remove an item" (see this discussion for more information).

Remove first element equal to needle
// Panic if no such element is found
vec.remove(vec.iter().position(|x| *x == needle).expect("needle not found"));

// Ignore if no such element is found
if let Some(pos) = vec.iter().position(|x| *x == needle) {
    vec.remove(pos);
}
Remove last element equal to needle

Like the first element, but replace position with rposition.

Remove all elements equal to needle
vec.retain(|x| *x != needle);
... or with swap_remove

Remember that remove has a runtime of O(n) as all elements after the index need to be shifted. Vec::swap_remove has a runtime of O(1) as it swaps the to-be-removed element with the last one. If the order of elements is not important in your case, use swap_remove instead of remove!

Difference between std::remove and vector::erase for vectors , In this article, we will go through multiple ways to delete elements from a vector container in C++ STL like pop_back, pop_front, erase, clear, remove and more. Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use: vec.erase(vec.begin() + index);


There is a position() method for iterators which returns the index of the first element matching a predicate. Related question: Is there an equivalent of JavaScript's indexOf for Rust arrays?

And a code example:

fn main() {
    let mut vec = vec![1, 2, 3, 4];

    println!("Before: {:?}", vec);

    let removed = vec.iter()
        .position(|&n| n > 2)
        .map(|e| vec.remove(e))
        .is_some();

    println!("Did we remove anything? {}", removed);

    println!("After: {:?}", vec);
}

Different ways to remove elements from vector in C++ STL, Erasing an element from a vector. Ex: v.erase(v.begin()+4); (erases the fifth element of the vector v). erase(int start,int end): Removes the elements in the range  std::remove does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container: std::vector<int> vec; // .. put in some values .. int int_to_remove = n; vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());


If your data is sorted, please use binary search for O(log n) removal, which could be much much faster for large inputs.

match values.binary_search(value) {
  Ok(removal_index) => values.remove(removal_index),
  Err(_) => {} // value not contained.
}

Vector-Erase, Since calling the erase() method on the vector element invalidates the iterator, special care needs to be taken while erasing an element. We can do that in many​  I just want to remove all the appearances of elements of A from the data vector. I gave the example [1,2] . The element 1 for example might appear 1000 (or not at all) times in data vector, and I want to delete all of them, and same for 2.


Remove elements from a vector inside a loop in C++, vector::erase() is a library function of "vector" header, it is used to erase/delete elements from the vector, it either removes one element from a  delete element from vector. Learn more about delete element from vector, cheat sheets


vector::erase() function with example in C++ STL, Remove an element from C++ std::vector<> by index can be done by following way −Example Live Demo#include #include using namespace  vector::erase : Removes from the vector either a single element (position) or a range of elements ([first, last)). std::remove vs vector::erase. By using erase all elements in a std::vector will be shifted by 1 causing a large amount of copies; std::remove does just a ‘logical’ delete and leaves the vector unchanged by moving things around. If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while


Removing an element from C++ std::vector<> by index?, pos, -, iterator to the element to remove. first, last, -, range of elements to remove. Type requirements. -. T must meet the requirements of  The java.util.vector.remove (int index) method is used to remove an element from a Vector from a specific position or index.