Better to use std::vector<std::unique_ptr<int>>
(or even std::vector<int>
if you don't need pointer).
then just use erase-remove idiom:
std::vector<int> intList{3, 2, 1};
intList.erase(std::remove(intList.begin(), intList.end(), 2), intList.end());
or
std::vector<std::unique_ptr<int>> intList;
intList.puch_back(std::make_unique<int>(3));
intList.puch_back(std::make_unique<int>(2));
intList.puch_back(std::make_unique<int>(1));
intList.erase(std::remove_if(intList.begin(), intList.end(),
[](const auto& p){ return *p == 2; }),
intList.end());
If you really need raw owning pointer, you may use a variant using partition
:
std::vector<int*> intList{ new int {3}, new int {2}, new int{1} };
auto it = std::partition(intList.begin(), intList.end(),
[](const auto& p){ return *p != 2; });
std::foreach (it, intList.end(), [](int* p) { delete p; });
intList.erase(it, intList.end());
Finally, if you really need to do it manually, you have to fix your erase line to:
it = intList.erase(it);
to have:
std::vector<int*> intList{ new int {3}, new int {2}, new int{1} };
for (auto it = intList.begin(); it != intList.end(); /*Empty*/) {
int *p = *it;
if (*p == 2) {
delete p;
it = intList.erase(it);
} else {
++it;
}
}