littleZ
littleZ

Reputation: 71

How to delete the last element of a forward_list?

I don't know how to delete the last element of the forward_list

forward_list<string> names {"fwfew","zhangwne","xiaobew","yaya","qiuqiu","haifeng"};

Upvotes: 1

Views: 747

Answers (2)

User
User

Reputation: 610

You are trying to remove the last element of the singly link list which is implemented as std::forward_list . It's obvious you can't do that without doing the second Last element of the list .

If you want to do this then there are many work arounds to iterate to second last and calling erase after .

and if you know how many elementa are there then ,

forward_list<string> names {"fwfew","zhangwne","xiaobew","yaya","qiuqiu","haifeng"};

auto next_val = std::next( names.begin(), 4 );
 
names.erase_after( next_val );

Upvotes: 0

eerorika
eerorika

Reputation: 238311

Ideally, you simply don't do that. If erasing the last element is an operation that you need to do, then it's likely that a forward list isn't the appropriate container for the use case.

That said, you can use linear search to find second to last iterator and use erase_after. In the case only one element exists, use pop_front instead.

Upvotes: 2

Related Questions