Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save std::set in std::list

Tags:

c++

list

set

I have a set:

std::set<Proc*> finalProc = getFinalProc();

I just want to copy all elements from this set into a list. I thought I have to iterate through the set and save the elements in the list? I guess I made a major mistake but I can't find a solution for this:

std::list<Proc*> firstLevel;
for(std::set<Processor*>::iterator it = endProcessors.begin(); it != endProcessors.end(); ++it){
    firstLevel.push_back( ???? );
}

The idea was to push_back all iterated elements?

like image 225
user2633791 Avatar asked Jul 25 '26 22:07

user2633791


1 Answers

There is a much better way to do that:

std::list<Proc*> firstLevel(finalProc.begin(), finalProc.end());

In your original code you should have replaced ???? with *it and endProcessors with finalProc

As @luk32 notes, possibly you have a bug (if you want to copy the actual data, not the pointers). In this case you can see @luk32 solution or I would go for std::unique_ptr here (smart pointers is a preferred way to manage memory in modern C++):

std::list<std::unique_ptr<Proc>> firstLevel;
for(const auto& ptr: finalProc){
    firstLevel.push_back(std::make_unique<Proc>(*ptr));
}

All memory pointed by pointers in firstLevel will be automatically freed after going out of firstLevel visibility scope.

like image 110
sasha.sochka Avatar answered Jul 28 '26 13:07

sasha.sochka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!