Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the first occurrence of a value from a vector?

Tags:

c++

c++11

I'm trying to get a single element from a vector and push it to the back of the vector then remove it so I won't have an empty section in memory. The erase-remove idiom can do this but it removes all instances of a particular value. I just want the first one removed.

I'm not too experienced with standard library algorithms and I can't find the appropriate methods (if any) to do this. Here is an example:

int main() {
    std::vector<int> v{1, 2, 3, 3, 4};

    remove_first(v, 3);

    std::cout << v; // 1, 2, 3, 4
}

So how would I go about removing the first occurance of a 3 from this vector?

like image 587
template boy Avatar asked Feb 06 '13 20:02

template boy


People also ask

How do you remove the first element of a vector?

erase() function is used to remove elements from a container from the specified position or range. Syntax : 1. vectorname.erase(position) 2.

How do you remove all occurrences of a number from a vector?

Using std::vector::erase Another option is to iterate over the vector and remove all the occurrences of the target from the vector using std::vector::erase function. That's all about removing all occurrences of an element from a vector in C++.

How do you remove a random element from a vector?

The idea is to swap the last element and an element you want to remove and then pop_back() . If you need to remove the last elemtent - just pop_back() . The order of the vector will not be the same but you get a fast remove method.


1 Answers

Find it first, then erase it:

auto it = std::find(v.begin(),v.end(),3);
// check that there actually is a 3 in our vector
if (it != v.end()) {
  v.erase(it);
}
like image 102
us2012 Avatar answered Oct 04 '22 20:10

us2012