Mike Short
0
Q:

how to remove an element from a vector by value c++

#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
std::vector<int> v; 
// fill it up somehow
v.erase(std::remove(v.begin(), v.end(), 99), v.end()); 
// really remove all elements with value 99
1
carVec.erase(std::remove_if(carVec.begin(), carVec.end(), [&id_to_delete](const Car& ele)->bool
            {
                return ele.getnewId() == id_to_delete;
            }), carVec.end());
1
#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
1
vector.erase(position) // remove certain position
// or
vector.erase(left,right) // remove positions within range
3
v.erase(std::remove_if(
    v.begin(), v.end(),
    [](const int& x) { 
        return x > 10; // put your condition here
    }), v.end());
// therefore elements > 10 are removed, leaving only elements<= 10
0
#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;
}
0
Input  : myvector= {1, 2, 3, 4, 5};
         myvector.clear();
Output : myvector= {}
0

New to Communities?

Join the community