Complexity of std::list::splice and other list containers

前端 未结 1 542
别那么骄傲
别那么骄傲 2020-12-17 08:15

I have some code which deals with various std::list objects, and I am currently using a very inefficient method of transferring content between them (I\'m iterating through

相关标签:
1条回答
  • 2020-12-17 08:57

    This was a very contentious topic during the standardization of C++11. The problem is that all standard containers, including lists, also have a constant-time size operation.

    Before C++11, many implementations made size linear time and splice between different lists constant time. C++11 now requires that size be constant and splice be linear.

    The problem is that, if the length of the spliced range isn't counted one-by-one, then the containers cannot keep track of how many elements were removed and added, and the next call to size would need to recover this information in O(N) time — using the larger N of the entire sequence, not just the spliced part.

    A non-standard list container can supply the desired operation, because so long as you don't need O(1) size, your argument is correct.

    As for other libraries… I'm not aware of one, but Boost should have one. (I checked, it doesn't, so someone go get started!) Since you clearly understand how to write your own, doing so might be less effort than contending with such a large library as Qt.

    If you don't need thread safety, you could implement a wrapper around std::list in which each container only owns a subrange of a singleton list. This would eliminate most of the programming effort in replicating the standard interface.

    0 讨论(0)
提交回复
热议问题