remove from a vector c++ code example

Example 1: remove element by index from vector c++

// 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);

Example 2: vector erase specific element

vector.erase( vector.begin() + 3 ); // Deleting the fourth element

Example 3: c++ remove element from vector

vector.erase(position) // remove certain position
// or
vector.erase(left,right) // remove positions within range

Example 4: erase an element from vector c++

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    //Insert values 1 to 10
    v.push_back(20);
    v.push_back(10);
    v.push_back(30);
    v.push_back(20);
    v.push_back(40);
    v.push_back(20);
    v.push_back(10);

    vector<int>::iterator new_end;
    new_end = remove(v.begin(), v.end(), 20);

    for(int i=0;i<v.size(); i++){
        cout << v[i] << " ";
    }
    //Prints [10 30 40 10]
    return 0;
}
C++Copy

Example 5: remove element by index from vector c++

// 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);

Example 6: 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;
}

Tags:

Cpp Example