Why doesn't `std :: forward_list :: insert_after` return the first element inserted like other sequence containers?

Why does std::forward_list::insert_after not return the first element inserted into other containers in the sequence, such as list and vector . Are there deliberate reasons?

+7
c ++
source share
3 answers

forward_list very different from other sequences, like insert_after . In order to return the first inserted element, it will have to use additional time and space to save this element, while the last element will be available as part of the insertion algorithm. Not only that, but returning the iterator to the first element inserted from the range will give you an iterator that you can use to insert in the middle of the range you just added, while the iterator allows you to add additional data to the end of the range.

+3
source share

I do not know the considerations of the committee, but here are mine:

You can insert multiple elements, for example. "range". See http://en.cppreference.com/w/cpp/container/forward_list/insert_after

Returning the first element will not be really valuable, since getting the first element is trivial - you already have an iterator after which it was inserted.

OTOH, going to the last inserted item can be expensive if you have added many nodes.

+1
source share

After reviewing for some time, here is my understanding.

1. Standard sequence containers

For containers with a normal sequence, insert takes an iterator (which I will call itl ) as a parameter and inserts the elements before itl . It then returns an iterator ( itf ) that points to the first element inserted. Now you have 2 iterators, separately designating the range (first and next) of the inserted elements.

 elem-elem-inserted-inserted-inserted-elem-elem | | (itf) (itl) 

However, the insert operation may invalidate the itl , so we need to consider the following two situations:

1.1 Related structure

For a linked structure, itl remains valid. Therefore ( itf , itl ) forms a valid range for inserted elements.

1.2 Continuous structure

For an adjacent structure, itl not valid after insertion. However, such structures usually support random access, so it is relatively easy to get itl through simple arithmetic on itf . On the other hand, returning the iterator to the first inserted element maintains consistency.

2. The forecast list

insert_after for forward-list takes an iterator ( itf ) as a parameter and inserts the elements after it. Then it returns the iterator to the last inserted element ( itl ). Since itf remains valid, we again have a similar range.

 elem-elem-inserted-inserted-inserted-elem-elem | | (itf) (itl) 

3. Conclusion

Regardless of whether the insert operation returns an iterator to the first inserted element or the last inserted element, it always tries to provide access to the beginning and end of the inserted elements at the same time, which provides maximum flexibility.

+1
source share

All Articles