简体   繁体   中英

How are STL containers in C++ actually implemented..

I get asked about this a lot. I have read various sources including the book from Bjarne Stroustrup. It says that the standard does not mandate any implementation for the STL containers. But I am still not clear. If there is no mandate on the implementation, does it mean that when using a vector or a list in my code , it may use a different data structures at different times?? And if it is the case, how is it decided which data structure will be used at which time?? I mean should it not be fixed that all STL containers will use a specific DS everytime??

该标准没有规定应该使用哪些数据结构来实现STL容器,但它确实提供了复杂性保证,有时还提供其他保证(如使用连续内存的vector ),这通常会限制合理使用的数据结构的选择。实施少数选择。

it may use a different data structures at different times?

Yes, it may. But we need to clearly define a "different time". If you compile it for platform P with standard library implementation I, then it will use the same data structure for as long as this program is run. If you change P or I and recompile, then another data structure may be used. "Different times" are separated by builds.

how is it decided which data structure will be used at which time?

The standard imposes asymptotic complexity requirements, so that's a big criteria right there. Beyond that, an implementer may choose between different data structures that meet those requirements. Since implementers are also aware of platforms, they may choose a data structure that behaves better on the particular platform you are building on.

I mean should it not be fixed that all STL containers will use a specific DS everytime?

No. What if someone comes up with a really cool and efficient data structure tomorrow, one that can completely meet and exceed the requirements of some standard library container? If the data structure is set fixed in the specification, instead of the complexity, it would not be allowed to use this better implementation. Not until the C++ standard is perhaps updated, a process that can take years.

Software engineering is about balancing specification and abstraction. You must specify what is required to solve a problem, and abstract the details that are not relevant to the solution. If you over specify, you lose flexibility. But be careful not to over abstract and lose performance. The standard library is a great case study of an attempt to balance the two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM