I want to try reversing a forward_list (without the reverse() method) but I'm not sure how to get rid of the last element after the erase_after() method without using resize().
#include<forward_list>
template<typename vt>
class reverse_forward_list{
public:
static void reverse(std::forward_list<vt>& list){
typename std::forward_list<vt>::iterator iter = list.begin();
int x = 0;
for(vt& i :list){
list.emplace_front(i);
x ;
}
list.erase_after(iter,list.end());
//list.resize(x);
}
};
Any help is appreciated
CodePudding user response:
Use list.before_begin()
instead to also erase the previous first element.
Also, this can be implemented more efficiently by splicing each node to the front of the list (which is probably how reverse
works internally, and you won't have to allocate new nodes/construct new values)
CodePudding user response:
IMHO there should be a VERY good reason for manipulating a list while traversing it... It's a disaster waiting to happen.
Instead, consider using a temporary list, something like that:
template<typename vt>
static void reverse(std::forward_list<vt>& list) {
std::forward_list<vt> newlist;
while (!list.empty()) {
newlist.push_front(list.front());
list.pop_front();
}
list = newlist;
}