Answer the question
In order to leave comments, you need to log in
An error occurred while deleting an element. How to remove an element from a list in C++?
Good day. I ask for help, because I can not understand where the error is. When an element is removed from the middle of a doubly linked list (the STL container list), the last element is duplicated.
Here is the removal code:
for (auto it = myList.begin(); it != myList.end();)
{
if (*it == 7)
it = myList.erase(it);
else
++it;
}
Answer the question
In order to leave comments, you need to log in
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
template<typename Container, typename value>
bool remove_value(Container& c, value v)
{
if(auto it{find(begin(c), end(c), v)}; it != end(c))
{
c.erase(it);
return true;
}
return false;
}
int main()
{
list<int> myList {1,2,3,4,5,6,7,8,9,10};
//myList.erase(std::remove(myList.begin(), myList.end(), 7));
/*if(auto it{find(myList.begin(), myList.end(), 7)}; it != myList.end())
{
myList.erase(it);
}*/
if(int value = 7; remove_value(myList, value))
{
cout << "removed value: " << value << endl;
}
else
{
cout << "value: " << value << " not found" << endl;
}
for(int v:myList)
{
std::cout << v << ' ';
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question