A
A
AlphaScript2018-08-06 16:45:33
C++ / C#
AlphaScript, 2018-08-06 16:45:33

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;
}

For example, myList = { 4, 5, 6, 7, 8, 10, 11 }, after removing 7, myList will be like this { 4, 5, 6, 8, 10, 11, 11 }
Thanks in advance for your help.
PS Do not judge strictly, I'm just starting to work with STL, and recently I've been writing in C ++ - better tell me how to do it better.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2018-08-06
@AlphaScript

spoiler
#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 << ' ';
    }
}

g++ -std=c++1z
You use STL containers... there are algorithms for them.
www.cplusplus.com/reference/algorithm
https://en.cppreference.com/w/cpp/algorithm

S
Stanislav Makarov, 2018-08-06
@Nipheris

Erase–remove idiom

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question