I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
std::vector<int>::iterator endIter = myNumbers_in.end();
for(; iter != endIter; ++iter)
{
if(*iter == number_in)
{
myNumbers_in.erase(iter);
}
}
}
int main(int argc, char* argv[])
{
std::vector<int> myNmbers;
for(int i = 0; i < 2; ++i)
{
myNmbers.push_back(i);
myNmbers.push_back(i);
}
erase(myNmbers, 1);
return 0;
}
This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector?
Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified).
Edit: While updating a dead link I discovered that starting in C++20 there are freestanding std::erase and std::erase_if functions that work on containers and simplify things considerably.
Calling erase will invalidate iterators, you could use:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
while (iter != myNumbers_in.end())
{
if (*iter == number_in)
{
iter = myNumbers_in.erase(iter);
}
else
{
++iter;
}
}
}
Or you could use std::remove_if together with a functor and std::vector::erase:
struct Eraser
{
Eraser(int number_in) : number_in(number_in) {}
int number_in;
bool operator()(int i) const
{
return i == number_in;
}
};
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());
Instead of writing your own functor in this case you could use std::remove:
std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());
In C++11 you could use a lambda instead of a functor:
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());
In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):
std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda
or:
std::vector<int> myNumbers;
std::erase(myNumbers, number_in);
You can iterate using the index access,
To avoid O(n^2) complexity
you can use two indices, i - current testing index, j - index to
store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial.
The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
There are std::erase and std::erase_if since C++20 which combines the remove-erase idiom.
std::vector<int> nums;
...
std::erase(nums, targetNumber);
or
std::vector<int> nums;
...
std::erase_if(nums, [](int x) { return x % 2 == 0; });
If you change your code as follows, you can do stable deletion.
void atest(vector<int>& container,int number_in){
for (auto it = container.begin(); it != container.end();) {
if (*it == number_in) {
it = container.erase(it);
} else {
++it;
}
}
}
However, a method such as the following can also be used.
void btest(vector<int>& container,int number_in){
container.erase(std::remove(container.begin(), container.end(), number_in),container.end());
}
If we must preserve our sequence’s order (say, if we’re keeping it sorted by some interesting property), then we can use one of the above. But if the sequence is just a bag of values whose order we don’t care about at all, then we might consider moving single elements from the end of the sequence to fill each new gap as it’s created:
void ctest(vector<int>& container,int number_in){
for (auto it = container.begin(); it != container.end(); ) {
if (*it == number_in) {
*it = std::move(container.back());
container.pop_back();
} else {
++it;
}
}
}
Below are their benchmark results:
CLang 15.0:
Gcc 12.2:
Related
A number of posts I've read lately claim for(const auto &it : vec) is the same as using the longer iterator syntax for(std::vector<Type*>::const_iterator it = vec.begin(); it != vec.end(); it++). But, I came upon this post that says they're not the same.
Currently, I'm trying to erase an element in a for loop, after it is used, and wondering if there is any way to convert const auto &it : nodes to std::vector<txml::XMLElement*>::iterator?
Code in question:
std::vector<txml2::XMLElement *> nodes;
//...
for (const auto &it : nodes)
{
//...
nodes.erase(it);
}
I pretty sure I could just rewrite std::vector<txml2::XMLElement*> as a const pointer, but would prefer not to since this code is just for debugging in the moment.
You should not be attempting to convert the range declaration in your range based for loop to an iterator and then deleting it whilst iterating. Even adjusting iterators while iterating is dangerous, and you should instead rely on algorithms.
You should use the Erase-remove idom.
You can use it with remove_if.
It would look something like:
nodes.erase( std::remove_if(nodes.begin(), nodes.end(), [](auto it){
//decide if the element should be deleted
return true || false;
}), nodes.end() );
Currently in the technical specifications, is erase_if.
This is a cleaner version of the same behaviour shown above:
std::erase_if(nodes,[](auto it){
//decide if the element should be deleted
return true || false;
});
You don't get an iterator but a reference to the element. Unless you want to do a std::find with it, it's pretty hard to get an iterator out of it.
Vectors are nice, so you could increase a counter per element and do nodes.begin() + counter to get the iterator, but it'd sort of defeat the point.
Also erasing the iterator in the for loop will result in you iterating after the end of the vector, you can test this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {0,1,2,3,4,5,6};
for (int x : v) {
cout << x << endl;
if (x == 2) {
v.erase(v.begin() + 2);
}
}
return 0;
}
If you want to use iterators, just do a loop with them, if in addition you want to erase one mid-loop you have to follow this answer:
for (auto it = res.begin() ; it != res.end(); ) {
const auto &value = *it;
if (condition) {
it = res.erase(it);
} else {
++it;
}
}
Note that you don't need to specify the whole type of the iterator, auto works just as well.
I have a vector<Suggestions> finalSuggestions that contains a string word and some int num.
If this word meets some condition, I want to move that object to the front of the vector, removing it from wherever it was.
I am able to insert to the beginning of the list with vector::insert
for (auto &x: finalSuggestions) {
if ( double((x.num)/(topword.num)) < 50)
{
finalSuggestions.insert(finalSuggestions.begin(),x);
break;
}
}
But I do not know how to remove it from where it is in the list.
For example, for some arbitrary vector { 1,2,3,4,50,6,7,8,9 },
if 50 meets the criteria, move it to the front of the list and delete it from where it was, returning { 50,1,2,3,4,6,7,8,9 }. The code above returns { 50,1,2,3,4,50,6,7,8,9 }
I was looking into vector::erase, but I'm having problems, and its taking longer than it should.
I envision a simple solution (but this obviously doesn't work)
for (auto &x: finalSuggestions) {
if ( double((x.num)/(topword.num)) < 50)
{
finalSuggestions.insert(finalSuggestions.begin(),x);
finalSuggestions.erase(x);
break;
}
}
I read up on the erase-remove idiom (here is my implementation):
finalSuggestions.erase( remove( begin(finalSuggestions), end(finalSuggestions), x ), end(finalSuggestions) );
but am getting an error that I don't understand:
In instantiation of '_FIter std::remove(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<Suggestion*, std::vector<Suggestion> >; _Tp = Suggestion]':|
Use std::rotate. It's a lot faster than deleting and reinserting.
Eg:
for (auto it = finalSuggestions.begin(), lim = finalSuggestions.end();
it != lim;
++it) {
if (it->num < 50 * topword.num) {
std::rotate(finalSuggestions.begin(), it, it + 1);
break;
}
}
Even better, as #JerryCoffin suggests in a comment, use std::find_if to find the pivot:
auto pivot = std::find_if(finalSuggestions.begin(),
finalSuggestions.end(),
[&topword](const Suggestions& s) -> bool {
return s.num < 50 * topword.num;
});
if (pivot != finalSuggestions.end()) {
std::rotate(finalSuggestions.begin(), pivot, pivot + 1);
}
For vector::erase you need an iterator, so range-based for can't be used. Use simple for loop instead. First erase an element, and then insert it, because insert invalidates iterators:
for (auto it = finalSuggestions.begin(); it != finalSuggestions.end(); ++it) {
if (some_condition(*it)) {
auto x = *it; // or std::move(*it)
finalSuggestions.erase(it);
finalSuggestions.insert(finalSuggestions.begin(), x /* or std::move(x) */);
break;
}
}
Using std::move will allow you to move an element around instead of copying it, which may save you some cycles.
Your iterator makes it difficult to know the position of the element in question. You might want to try using a standard for iterator which allows access to the position (used by std::vector::erase)
int len=finalSuggestions.size();
for (int i=0, ; i<len; ++i) {
// Save a copy of the item
auto item = finalSuggestions.at(i);
if (double((item.num)/(topword.num)) < 50) {
// Erase the item in the list
finalSuggestions.erase(i);
// Add the copy of the item back in at the front
finalSuggestions.insert(finalSuggestions.begin(), item);
break;
}
}
... or using a std::iterator ...
for (auto it = finalSuggestions.begin(); it != finalSuggestions.end(); ++it) {
if (double((*it->num)/(topword.num)) < 50) {
// Save a copy of the item
auto item = *it;
// Erase the item in the list
finalSuggestions.erase(it);
// Add the copy of the item back in at the front
finalSuggestions.insert(finalSuggestions.begin(), item);
break;
}
}
std::vector objects use contiguous memory for their elements, which means actually moving memory around during altering of the container. If you are going to be moving elements around you may want to look into std::list or std:deque. The definition of these containers are nearly identical (read: drop in replacements) to each other making it fairly straight-forward to replace them.
Suggestion:
The std::deque is designed for optimal insertions at both the beginning and the end of the container. Taken from the site cplusplus.com:
... they provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: ...
Anton's answer is correct. However if you do this sort of thing a lot you should consider a different data structure. Both the erase and the insert are O(N) operations, where N is the size of the vector. A list would be better if this is a common operation.
It is functionally equivalent to Anton's answer, but I would use std::find_if to get the an iterator to the element you are looking for instead of a loop.
//add #include <algorithm> to your source file
auto result = std::find_if(finalSuggestions.begin(), finalSuggestions.end(), condition_func);
if(result != finalSuggestions.end())
{
auto resultValue = *result;
finalSuggestions.erase(result);
finalSuggestions.insert(finalSuggestions.begin(), resultValue);
}
condition_func should be a function returning bool that takes a parameter matching the type of the elements in your vector (in this case, Suggestion):
bool condition_func(Suggestion elementValue) { /*condition here*/ }
More information on find_if is available here.
Maybe using std::iter_swap could solve your problem.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
vector<int> myvector{};
for(int io{}; io<7; ++io) myvector.push_back(io+1);
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
cout << ' ' << *it;
cout << '\n';
iter_swap(myvector.begin(),myvector.begin()+2);//exchange the third element with the first.
cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Suppose now I have a list of data which is kept in a vector a. What I am going to do is to check whether each element in the data list is satisfied with some criteria. If it does, it will be removed from a and then be kept in another vector b. For example, in the following codes I can easily finish this task:
class findOddClass
{
public:
int Common;
findOddClass(int common):Common(common){};
bool operator()(const int &i)
{
return (i%Common == 1);
}
};
void testFunctionObject()
{
std::vector<int> objArray;
for(int i=0; i<10; i++)
objArray.push_back(i);
findOddClass finder(2);
std::vector<int>::iterator it = objArray.begin();
std::vector<int> oddArray;
while(it != objArray.end())
{
if (finder(*it))
{
oddArray.push_back(*it);
it = objArray.erase(it);
}
else
it++;
}
std::cout<<"Even array"<<std::endl;
for(it=objArray.begin(); it != objArray.end(); it++)
std::cout<<*it<<" ";
std::cout<<std::endl;
std::cout<<"Odd array"<<std::endl;
for(it= oddArray.begin(); it!=oddArray.end(); it++)
std::cout<<*it<<" ";
std::cout<<std::endl;
}
However, if I want to finish the same task with a more elegant way:
void testFunctionObject()
{
std::vector<int> objArray;
for(int i=0; i<10; i++)
objArray.push_back(i);
std::vector<int>::iterator itEnd;
itEnd = std::remove_if(objArray.begin(),objArray.end(),findOddClass(2));
std::vector<int> oddArray;
std::vector<int>::iterator it = itEnd;
while(it != objArray.end())
{
oddArray.push_back(*it);
it++;
}
objArray.erase(itEnd,objArray.end());
std::cout<<"Even array"<<std::endl;
for(it=objArray.begin(); it != objArray.end(); it++)
std::cout<<*it<<" ";
std::cout<<std::endl;
std::cout<<"Odd array"<<std::endl;
for(it= oddArray.begin(); it!=oddArray.end(); it++)
std::cout<<*it<<" ";
std::cout<<std::endl;
}
It will fail. The reason lies in the fact that std::removal_if will not keep a trace of the element that will be removed. I was just wondering whether there is a function in STL can do the job, hence a more elegant way of doing the job. Thanks.
I would suggest to use algorithm std::partition_copy if you want to split an original sequence in two sequences depending on some predicate. As the algorithm returns a pair of output iterators it will be easy to apply method erase using the result of the previous call of std::partition_copy
template <class InputIterator, class OutputIterator1,
class OutputIterator2, class Predicate>
pair<OutputIterator1, OutputIterator2>
partition_copy(InputIterator first, InputIterator last,
OutputIterator1 out_true, OutputIterator2 out_false,
Predicate pred);
std::partition is very efficient for moveable elements. Sketched out, the code would look something like this:
auto partition_point = std::partition(v1.begin(), v1.end(), predicate);
// Move the elements at the range to the other vector.
v2.assign(std::make_move_iterator(partition_point),
std::make_move_iterator(v1.end()));
// Remove the remains from the original.
v1.erase(partition_point, v1.end());
The advantage over the partition_copy solution is that there is zero actual copying going on, which make this more efficient for handle-like things like std::string, or move-only types.
I've been working on learning python and somehow came up with following codes:
for item in list:
while list.count(item)!=1:
list.remove(item)
I was wondering if this kind of coding can be done in c++. (Using list length for the for loop while decreasing its size) If not, can anyone tell me why?
Thanks!
I am not a big Python programmer, but it seems like the above code removes duplicates from a list. Here is a C++ equivalent:
list.sort();
list.unique();
As for modifying the list while iterating over it, you can do that as well. Here is an example:
for (auto it = list.begin(), eit = list.end(); it != eit; ) {
if (std::count(it, eit, *it) > 1)
it = list.erase(it);
else
++it;
}
Hope it helps.
In C++, you can compose something like this from various algorithms of the standard library, check out remove(), find(), However, the way your algorithm is written, it looks like O(n^2) complexity. Sorting the list and then scanning over it to put one of each value into a new list has O(n log n) complexity, but ruins the order.
In general, both for Python and C++, it is often better to copy or move elements to a temporary container and then swap with the original than modifying the original in-place. This is easier to get right since you don't step on your own feet (see delnan's comment) and it is faster because it avoids repeated reallocation and copying of objects.
Here's how I'd do it.
//If we will not delete an element of the list
for (std::list<MyType>::iterator it = MyList.begin(); it != MyList.end();++it)
{
//my operation here
}
//If we will delete an element of the list
for (std::list<MyType>::iterator it = MyList.begin(); it != MyList.end();)
{
std::list<MyType>::iterator itt = it;
++itt;
MyList.erase(it);
it = itt;
}
You can use the size of the list, but it is not comparable to [it] because [it].
Certain features of std:: data classes are enabled or disabled as a design decision. Sure, you can make your own function MyList[int i], but it will lead to a large speed gimp due to the nature of lists.
In C++ you can in some conditions remove elements from a container while iterating over it. This depends on the container and on the operation you want to do.
Currently there are different interpretations of your code snipplet in the different answers. My interpretation is, that you want to delete all the elements which exists more than once in the list.
Here is the solution in C++: it first counts the elements in another container (std::map) and removes the appropriate elements from the list afterwards.
#include <list>
#include <map>
#include <algorithm>
#include <iostream>
int main() {
std::list<int> li { 0, 1, 2, 3, 4, 5, 1, 2, 3, 2, 2 };
// Create count map: element -> count
std::map<int, int> cm;
std::for_each( li.begin(), li.end(), [&cm](int i) { ++cm[i]; } );
// Remove all elements from list with count > 1
std::for_each( cm.begin(), cm.end(),
[&li](std::pair<const int, int> const p) {
if( p.second > 1) {
li.remove( p.first );
}
} );
// Output all elements from remaining list
std::for_each( li.begin(), li.end(),
[](int i) { std::cout << i << std::endl; } );
return 0;
}
I don't know Python but someone said in a comment that a list is equivalent to a C++ vector and it is not sorted, so here goes....
std::vector<int> v{1, 2, 2, 2, 3, 3, 2, 2, 1};
v.erase(std::unique(v.begin(), v.end()), v.end());
v contains {1, 2, 3, 2, 1} after this code. If the goal is to remove all duplicates (not just consecutive duplicates) you'll have to sort the vector first: std::sort(v.begin(), v.end());
std::vector is the container in C++ that is most similar to Python's list, and here's the correct way to modify a vector while iterating it:
template <typename T>
void dedupe(std::vector<T> &vec) {
for (std::vector<T>::iterator it = vec.begin(); it != vec.end(); ) {
if (std::count(vev.begin(), vec.end(), *it) != 1) {
it = vec.erase(it);
} else {
++it;
}
}
}
It's not necessarily the most efficient way to dedupe, but it works.
Using list length for the for loop while decreasing its size
If you insist on using the length rather than the end(), then you can use an index instead of an iterator:
template <typename T>
void dedupe(std::vector<T> &vec) {
for (std::vector<T>::size_type pos = 0; pos != vec.size(); ) {
if (std::count(vec.begin(), vec.end(), vec[pos]) != 1) {
vec.erase(vec.begin() + pos);
} else {
++pos;
}
}
}
I'm assuming that the intention of your Python code is to remove all duplicates, by the way, and that the fact it doesn't is a bug. For example input [2,2,1,3,3,1,2,3], output [1,1,2,3]. If what you said is what you meant, then a direct translation of your code to C++ is:
template <typename T>
void dedupe(std::vector<T> &vec) {
for (std::vector<T>::size_type pos = 0; pos < vec.size(); ++pos) {
T item = vec[pos];
while (std::count(vec.begin(), vec.end(), item) != 1) {
vec.erase(std::find(vec.begin(), vec.end(), item));
}
}
}
I want to remove some elements from a vector and am using remove_if algorithm to do this. But I want to keep track of the removed elements so that I can perform some operation on them later. I tried this with the following code:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct IsEven
{
bool operator()(int n)
{
if(n % 2 == 0)
{
evens.push_back(n);
return true;
}
return false;
}
vector<int> evens;
};
int main(int argc, char **argv)
{
vector<int> v;
for(int i = 0; i < 10; ++i)
{
v.push_back(i);
}
IsEven f;
vector<int>::iterator newEnd = remove_if(v.begin(), v.end(), f);
for(vector<int>::iterator it = f.evens.begin(); it != f.evens.end(); ++it)
{
cout<<*it<<"\n";
}
v.erase(newEnd, v.end());
return 0;
}
But this doesn't work as remove_if accepts the copy of my functor object, so the the stored evens vector is not accessible. What is the correct way of achieving this?
P.S. : The example, with even and odds is just for example sake, my real code is somethinf different. So don't suggest a way to identify even or odds differently.
The solution is not remove_if, but it's cousin partial_sort partition. The difference is that remove_if only guarantees that [begin, middle) contains the matching elements, but partition also guarantees that [middle, end) contains the elements which didn't match the predicate.
So, your example becomes just (note that evens is no longer needed):
vector<int>::iterator newEnd = partition(v.begin(), v.end(), f);
for(vector<int>::iterator it = newEnd; it != v.end(); ++it)
{
cout<<*it<<"\n";
}
v.erase(newEnd, v.end());
Your best bet is std::partition() which will rearrange all elts in the sequence such as all elts for which your predicate return true will precede those for which it returns false.
Exemple:
vector<int>::iterator bound = partition (v.begin(), v.end(), IsEven);
std::cout << "Even numbers:" << std::endl;
for (vector<int>::iterator it = v.begin(); it != bound; ++it)
std::cout << *it << " ";
std::cout << "Odd numbers:" << std::endl;
for (vector<int>::iterator it = bound; it != v.end(); ++it)
std::cout << *it << " ";
You can avoid copying your functor (i.e. pass by value) if you pass ist by reference like this:
vector<int>::iterator newEnd = remove_if(v.begin(), v.end(),
boost::bind<int>(boost::ref(f), _1));
If you can't use boost, the same is possible with std::ref. I tested the code above and it works as expected.
An additional level of indirection. Declare the vector locally, and
have IsEven contain a copy to it. It's also possible for IsEven to
own the vector, provided that it is dynamically allocated and managed by
a shared_ptr. In practice, I've generally found the local variable
plus pointer solution more convenient. Something like:
class IsEven
{
std::vector<int>* myEliminated;
public:
IsEven( std::vector<int>* eliminated = NULL )
: myEliminated( eliminated )
{
}
bool
operator()( int n ) const
{
bool results = n % 2 == 0;
if ( results && myEliminated != NULL ) {
myEliminated->push_back( n );
}
return results;
}
}
Note that this also allows the operator()() function to be const. I
think this is formally required (although I'm not sure).
The problem that I see with the code is that the evens vector that you create inside the struct gets created everytime the remove_if algorithm calls it. So no matter if you pass in a functor to remove_if it will create a new vector each time. So once the last element is removed and when the function call ends and comes out of the function the f.evens will always fetch an empty vector. This could be sorted in two ways,
Replace the struct with a class and declare evens as static (if that is what you wanted)
Or you could make evens global. I wouldn't personally recommend that( it makes the code bad, say no to globals unless you really need them).
Edit:
As suggested by nabulke you could also std::ref something likke this, std::ref(f). This prevents you from making the vector global and avoids for unnecessary statics.
A sample of making it global is as follows,
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> evens;
struct IsEven
{
bool operator()(int n)
{
if(n % 2 == 0)
{
evens.push_back(n);
return true;
}
return false;
}
};
int main(int argc, char **argv)
{
vector<int> v;
for(int i = 0; i < 10; ++i)
{
v.push_back(i);
}
IsEven f;
vector<int>::iterator newEnd = remove_if(v.begin(), v.end(), f);
for(vector<int>::iterator it = evens.begin(); it != evens.end(); ++it)
{
cout<<*it<<"\n";
}
v.erase(newEnd, v.end());
return 0;
}
This code seems to work just fine for me. Let me know if this is not what you wanted.
You may have another solution; only if you don't need to remove elts in the same time (do you?). With std::for_each() which returns a copy of your functor. Exemple:
IsEven result = std::for_each(v.begin(), v.end(), IsEven());
// Display the even numbers.
std::copy(result.evens.begin(), result.evens.end(), std::ostream_iterator<int> (cout, "\n"));
Take note that it is always better to create unnamed variables in c++ when possible. Here that solution does not exactly answer your primary issue (removing elts from the source container), but it reminds everyone that std::for_each() returns a copy of your functor. :-)