Pop a Specific Element off a Vector in C++

so suppose I have a vector called v and it has three elements: 1,2,3

is there a way to specifically pop 2 from the vector so the resulting vector becomes

1,3

4 Answers

//erase the i-th element
myvector.erase (myvector.begin() + i);

(Counting the first element in the vector as as i=0)

3

Assuming you're looking for the element containing the value 2, not the value at index 2.

#include<vector>
#include<algorithm>

int main(){
   std::vector<int> a={1,2,3};
   a.erase(std::find(a.begin(),a.end(),2));
}

(I used C++0x to avoid some boilerplate, but the actual use of std::find and vector::erase doesn't require C++0x)

2

Also, remember to use the erase-remove idiom if you are removing multiple elements.

#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;
  vector<unsigned int> myvector;

  // set some values (from 1 to 10)
  for (i=1; i<=10; i++) myvector.push_back(i);

  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);

  cout << "myvector contains:";
  for (i=0; i<myvector.size(); i++)
    cout << " " << myvector[i];
  cout << endl;

  return 0;
}
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest