- Mastering C++ Programming
- Jeganathan Swaminathan
- 227字
- 2021-07-02 18:28:50
Pitfalls of a vector
Every STL container has its own advantages and disadvantages. There is no single STL container that works better in all the scenarios. A vector internally uses an array data structure, and arrays are fixed in size in C/C++. Hence, when you attempt to add new values to the vector at the time the vector size has already reached its maximum capacity, then the vector will allocate new consecutive locations that can accommodate the old values and the new value in a contiguous location. It then starts copying the old values into the new locations. Once all the data elements are copied, the vector will invalidate the old location.
Whenever this happens, the vector insertion will take O(N) runtime complexity. As the size of the vector grows over time, on demand, the O(N) runtime complexity will show up a pretty bad performance. If you know the maximum size required, you could reserve so much initial size upfront in order to overcome this issue. However, not in all scenarios do you need to use a vector. Of course, a vector supports dynamic size and random access, which has performance benefits in some scenarios, but it is possible that the feature you are working on may not really need random access, in which case a list, deque, or some other container may work better for you.
- Java程序設計與開發
- ASP.NET Core 5.0開發入門與實戰
- 編寫整潔的Python代碼(第2版)
- 三維圖形化C++趣味編程
- 基于Swift語言的iOS App 商業實戰教程
- Unreal Engine 4 Shaders and Effects Cookbook
- Mastering JavaScript Design Patterns(Second Edition)
- ANSYS Fluent 二次開發指南
- Visual Foxpro 9.0數據庫程序設計教程
- Mastering Akka
- Building Dynamics CRM 2015 Dashboards with Power BI
- Python語言科研繪圖與學術圖表繪制從入門到精通
- OpenCV with Python Blueprints
- Google Maps JavaScript API Cookbook
- Spring Web Services 2 Cookbook