Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Loop through a set/list and remove the current entry

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

#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, 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading