Home > OS >  C Loop through a set/list and remove the current entry
C Loop through a set/list and remove the current entry

Time:12-10

Hey I loop through a list of integers, check each one by one if it equals number x and if so remove it from the list.

I tried it like that:

std::set<uintptr_t> uniquelist = {0, 1, 2, 3, 4};

for (auto listval : uniquelist) 
{                    
    if (listval == 2)
    {
        uniquelist.erase(listval);
    }
}

//Output = 0, 1, 3, 4

this way it crashes somehow instead of removing the current entry from the list. I know that there are easier methods for the example above, but I simplified it a lot to show what I want to achieve here. The list has to be std::set in my case.

CodePudding user response:

#include <iostream>
#include <set>
using namespace std;
void showContentSet(set<int>& input)
{
    for(auto iterator=input.begin(); iterator!=input.end();   iterator)
    {
        cout<<*iterator<<", ";
    }
    return;
}
void solve()
{
    set<int> uniqueSet={0, 1, 2, 3, 4};
    cout<<"Before, uniqueSet <- ";
    showContentSet(uniqueSet);
    cout<<endl;
    auto iterator=uniqueSet.find(2);
    uniqueSet.erase(iterator);
    cout<<"After, uniqueSet <- ";
    showContentSet(uniqueSet);
    cout<<endl;
    return;
}
int main()
{
    solve();
    return 0;
}

Here is the result:

Before, uniqueSet <- 0, 1, 2, 3, 4, 
After, uniqueSet <- 0, 1, 3, 4, 

CodePudding user response:

From https://en.cppreference.com/w/cpp/container/list/erase:

for (auto it = c.begin(); it != c.end(); ) {
    if (*it % 2 == 0) {
        it = c.erase(it);
    } else {
          it;
    }
}

std::list::erase() and std::set::erase() return the iterator to the next element, so you can just continue after erasing with that iterator, like in the example.

Also: the erase function parameter is an iterator, not a value.

  •  Tags:  
  • c
  • Related