remove value from vector c++ code example
Example 1: remove value from vector c++
#include
#include
// using the erase-remove idiom
std::vector vec {2, 4, 6, 8};
int value = 8 // value to be removed
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
Example 2: c++ remove element from vector
vector.erase(position) // remove certain position
// or
vector.erase(left,right) // remove positions within range
Example 3: remove element by index from vector c++
// Why not setup a lambda you can use again & again
auto removeByIndex =
[](std::vector &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 stringvec = {"Hello", "World"};
// Will remove index 1: "World"
removeByIndex(stringvec, 1);
// Vector of integers, we will use push_back
std::vector intvec;
intvec.push_back(33);
intvec.push_back(66);
intvec.push_back(99);
// Will remove index 2: 99
removeByIndex(intvec, 2);