Std::list.erase(), похоже, переставляет элементы списка ⇐ C++
-
Anonymous
Std::list.erase(), похоже, переставляет элементы списка
Consider the following function
void removeOdd(list& li) { for(list::iterator it=li.begin(); it!=li.end(); it++) { if((*it)%2) it = li.erase(it); } } From my understanding of lists, where the return value is an "iterator pointing to the element that followed the last element erased by the function call",
std::list.erase() documentation
the removeOdd() function should ignore the element after the element erased and carry on through the list.
However, when linked into this test script
#include #include #include #include #include using namespace std; void test() { int a[9] = { 5, 2, 8, 9, 6, 7, 3, 4, 1 }; list x(a, a+9); // construct x from the array assert(x.size() == 9 && x.front() == 5 && x.back() == 1); removeOdd(x); assert(x.size() == 4); vector v(x.begin(), x.end()); // construct v from x sort(v.begin(), v.end()); int expect[4] = { 2, 4, 6, 8 }; for (int k = 0; k < 4; k++){ assert(v[k] == expect[k]); } } int main() { test(); cout
Источник: https://stackoverflow.com/questions/781 ... f-the-list
Consider the following function
void removeOdd(list& li) { for(list::iterator it=li.begin(); it!=li.end(); it++) { if((*it)%2) it = li.erase(it); } } From my understanding of lists, where the return value is an "iterator pointing to the element that followed the last element erased by the function call",
std::list.erase() documentation
the removeOdd() function should ignore the element after the element erased and carry on through the list.
However, when linked into this test script
#include #include #include #include #include using namespace std; void test() { int a[9] = { 5, 2, 8, 9, 6, 7, 3, 4, 1 }; list x(a, a+9); // construct x from the array assert(x.size() == 9 && x.front() == 5 && x.back() == 1); removeOdd(x); assert(x.size() == 4); vector v(x.begin(), x.end()); // construct v from x sort(v.begin(), v.end()); int expect[4] = { 2, 4, 6, 8 }; for (int k = 0; k < 4; k++){ assert(v[k] == expect[k]); } } int main() { test(); cout
Источник: https://stackoverflow.com/questions/781 ... f-the-list
Мобильная версия