Search code examples
c++liststliteratorerase

erase() in list does not work in c++ on MacOS. What is bash: line 1: 88225 Segmentation fault: 11?


#include <iostream>
#include <list>
using namespace std;


int main () {
    list<int> mylist;
    list<int>::iterator it;

    for(int i=1;i<6;i++){
        mylist.push_back(i);
    }
    for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << ' ' << *it;
    cout<<endl;

    for(it=mylist.begin(); it!=mylist.end();it++){
        if((*it)==2){
            mylist.erase(it);
            mylist.insert(it,9);
            break;
        }
    }
    
    for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << ' ' << *it;
    cout<<endl;
    return 0;
}

It seems that mylist.erase(it) is not working because when I delete it, the program works.

The output for the above program is

1 2 3 4 5 bash: line 1: 88370 Segmentation fault: 11 "/Users/alimtleuliyev/Desktop/quiadratic" [Finished in 441ms with exit code 139]


Solution

  • You need to write

       if((*it)==2){
            it = mylist.erase(it);
            mylist.insert(it,9);
            break;
        }
    

    To output the list it is better to use the range-based for loop.

    Also to find an element in the list with the given value it is better to use the standard algorithm std::find instead of using a for loop.

    Here is a demonstration program.

    #include <iostream>
    #include <list>
    #include <iterator>
    #include <algorithm>
    
    int main()
    {
        std::list<int> mylist;
    
        for ( int i = 1; i < 6; i++ ) 
        {
            mylist.push_back( i );
        }
    
        for (const auto &item : mylist)
        {
            std::cout << item << ' ';
        }
        std::cout << std::endl;
    
        auto it = std::find( std::begin( mylist ), std::end( mylist ), 2 );
    
        if ( it != std::end( mylist) )
        {
            it = mylist.erase( it );
            mylist.insert( it, 9 );
        }
    
        for (const auto &item : mylist)
        {
            std::cout << item << ' ';
        }
        std::cout << std::endl;
            
        return 0;
    }
    

    The program output is

    1 2 3 4 5
    1 9 3 4 5
    

    Pay attention to that instead of calling the member functions erase and insert you could just write

        if ( it != std::end( mylist) ) *it = 9;