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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With