0
Q:

vector erase

// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);
17
#include <algorithm>
#include <vector>

// using the erase-remove idiom

std::vector<int> vec {2, 4, 6, 8};
int value = 8 // value to be removed
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
10
vector.erase(position) // remove certain position
// or
vector.erase(left,right) // remove positions within range
3
// CPP program to illustrate 
// working of erase() function 
#include <iostream> 
#include <vector> 
using namespace std; 
  
int main() 
{ 
    vector<int> myvector{ 1, 2, 3, 4, 5 }; 
    vector<int>::iterator it; 
  
    it = myvector.begin(); 
    myvector.erase(it); 
  
    // Printing the Vector 
    for (auto it = myvector.begin(); it != myvector.end(); ++it) 
        cout << ' ' << *it; 
    return 0; 
} 
0
// Why not setup a lambda you can use again & again
auto removeByIndex = 
  []<class T>(std::vector<T> &vec, unsigned int index)
{
	// This is the meat & potatoes
  	vec.erase(vec.begin() + index);
};

// Then you can throw whatever vector at it you desire
std::vector<std::string> stringvec = {"Hello", "World"};
// Will remove index 1: "World"
removeByIndex(stringvec, 1);
// Vector of integers, we will use push_back
std::vector<unsigned int> intvec;
intvec.push_back(33);
intvec.push_back(66);
intvec.push_back(99);
// Will remove index 2: 99
removeByIndex(intvec, 2);
0

New to Communities?

Join the community