There are a few posts around iterators with lists here using the insert
and splice
here functions but I am still not able to translate them for my case, I am iterating across a list and if a condition is meet I want to splice (move) the element to another list, but as stated here the iterator jumps to the splices container. How can I keep the iterator related to the original loop as in the example below.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <list>
using namespace std;
class Individual {
public:
Individual(bool state) : state_(state) {}
bool my_state(void) {
return state_;
}
private:
bool state_ = true;
};
int main () {
cout << "----------Enter Main----------" << endl;
list<Individual> list_individuals;
list<Individual> cache_list_individuals;
// initialise
for (auto i = 0; i < 100; ++i) {
if (i <= 50)
list_individuals.push_back(new Individual(true));
else
list_individuals.push_back(new Individual(false));
}
unsigned counter = 0;
for (auto iter = list_individuals.begin(); iter != list_individuals.end(); ++iter, ++counter) {
if ((*iter).my_state()) {
cache_list_individuals.splice(cache_list_individuals.begin(),list_individuals, iter);
// I need to make the iterator related to list_individuals not cache_list_individuals
}
}
cout << "----------Exit Main----------" << endl;
system("PAUSE");
return 0;
}