remove vector element c++ code example
Example 1: remove element by index from vector c++
vec.erase(vec.begin() + 1);
vec.erase(vec.begin() + 1, vec.begin() + 3);
Example 2: remove value from vector c++
#include <algorithm>
#include <vector>
std::vector<int> vec {2, 4, 6, 8};
int value = 8
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
Example 3: delete from front in vector c++
vector_name.erase(vector_name.begin());
vector_name.erase(vector_name.begin()+(x-1));
vector_name.pop_back();
Example 4: remove element by index from vector c++
auto removeByIndex =
[]<class T>(std::vector<T> &vec, unsigned int index)
{
vec.erase(vec.begin() + index);
};
std::vector<std::string> stringvec = {"Hello", "World"};
removeByIndex(stringvec, 1);
std::vector<unsigned int> intvec;
intvec.push_back(33);
intvec.push_back(66);
intvec.push_back(99);
removeByIndex(intvec, 2);
Example 5: how to delete an element in vector pair in cpp
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main()
{
vector< pair<int, int> > v;
int N = 5;
const int threshold = 2;
for(int i = 0; i < N; ++i)
v.push_back(make_pair(i, i));
int i = 0;
while(i < v.size())
if (v[i].second > threshold)
v.erase(v.begin() + i);
else
i++;
for(int i = 0; i < v.size(); ++i)
cout << "(" << v[i].first << ", " << v[i].second << ")\n";
cout << "Done" << endl;
}
Example 6: vector erase specific element
template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
std::vector<T>::iterator it = vec.begin();
std::advance(it, pos);
vec.erase(it);
}