Question

I understand why std::forward_list does not have a size() member function, since an O(1) version would mess up the complexity of certain splice() overloads, and since an O(N) version would be inconsistent with all the rest of the Standard Library's containers.

It is also true that both std::list and std::forward_list already have several other member functions with the same semantics as their cousins from the <algorithm> corner of the Standard Library (merge(), reverse(), remove(), remove_if(), unique(), sort()).

So why wasn't a count() member function of O(N) complexity provided to std::forward_list that had the semantics of returning std::distance(std::begin(some_list), std::end(some_list))?

Was it helpful?

Solution

The member functions you mention (merge(), reverse(), remove(), remove_if(), unique(), sort()) are provided because they have better complexity than the generic algorithms in the <algorithm> standard headers.

A member function such as count(), on the other hand, would not have better complexity than std::distance(std::begin(some_list), std::end(some_list)).

Also, it may be misinterpreted as the better-complexity version of the std::count generic algorithm, which does something basically different.

OTHER TIPS

The reason is that because, unlike the functions you listed, using the standard library algorithm for a count or size function would be just as fast a version that had direct access to the underlying implementation.

Each of the member functions you mentioned for std::forward_list are actually faster when implemented as members. In particular, they can operate without performing any unnecessary copies or moves of the contained data. The standard library algorithm versions require the data in the container to be copied or moved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top