官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 若尔盖县| 襄汾县| 调兵山市| 浠水县| 广宗县| 靖安县| 宝鸡市| 临潭县| 宜阳县| 河东区| 凤城市| 隆安县| 岳阳县| 县级市| 乐东| 汤原县| 南城县| 华阴市| 临沧市| 湛江市| 晋宁县| 贡觉县| 金阳县| 祁东县| 苍梧县| 颍上县| 南平市| 东乌珠穆沁旗| 库尔勒市| 信宜市| 汤原县| 出国| 灌阳县| 托克托县| 正镶白旗| 鲁甸县| 连云港市| 杨浦区| 全州县| 新竹县| 辰溪县|