TigerTV.ru
TigerTV.ru

Reputation: 1086

Move the first element to the end of the forward_list

I know that std::forward_list is a single linked list. I'm wondering how to move the first element(head) to the end of the forward_list. No copies or creating new nodes!

I've tried the following:

std::forward_list<int> l2 = {10,11,12};
auto beginIt = l2.begin();
beginIt = std::next(beginIt);
l2.splice_after(l2.end(),l2,l2.begin(),beginIt); 

for(int n : l2)
    std::cout << n << ' ';
std::cout << '\n';

But it doesn't work. Is there a way to do that?

Upvotes: 3

Views: 461

Answers (2)

T.C.
T.C.

Reputation: 137310

For your purposes, splice_after needs an iterator to the last element. That is, the element right before end(). There's no cheap way to get this:

auto pos = l2.begin();
while(std::next(pos) != l2.end()) ++pos;

Then, splice_after for a single element asks for an iterator pointing before that element. For the first element, that is before_begin():

l2.splice_after(pos, l2, l2.before_begin()); 

Upvotes: 3

chenzhongpu
chenzhongpu

Reputation: 6871

You could use rotate:

std::rotate(l.begin(), std::next(l.begin()), l.end());

Upvotes: 1

Related Questions