std :: vector resize下来 [英] std::vector resize downward

查看:358
本文介绍了std :: vector resize下来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准似乎没有通过
resize(n)表示对容量的副作用的陈述,其中n <

它会做一个关于push_back和pop_back - O(1)的摊销成本的说明



我可以设想一种实现常规类型的容量变化的实现。
ala CLRS算法(例如,当放大时加倍,当减小大小到< capacity()/ 4)时减半。
(Cormen Lieserson Rivest Stein)



有没有人有任何实现限制的参考?

解决方案

调用更小尺寸的resize()不会影响向量的容量。



从向量中释放内存的标准习语是用一个空的临时向量交换(): std: :vector< T>()。swap(vec); 。如果你想向下调整大小,你需要从你的原始向量复制到一个新的本地临时向量,然后用你的原来的交换结果的向量。



更新: C ++ 11添加了一个成员函数 shrink_to_fit() 为了这个目的,它是一个非绑定请求减少 capacity() size()


the C++ standard seems to make no statement regarding side-effects on capacity by either resize(n), with n < size(), or clear().

It does make a statement about amortized cost of push_back and pop_back - O(1)

I can envision an implementation that does the usual sort of capacity changes ala CLRS Algorithms (eg double when enlarging, halve when decreasing size to < capacity()/4). (Cormen Lieserson Rivest Stein)

Does anyone have a reference for any implementation restrictions?

解决方案

Calling resize() with a smaller size has no effect on the capacity of a vector. It will not free memory.

The standard idiom for freeing memory from a vector is to swap() it with an empty temporary vector: std::vector<T>().swap(vec);. If you want to resize downwards you'd need to copy from your original vector into a new local temporary vector and then swap the resulting vector with your original.

Updated: C++11 added a member function shrink_to_fit() for this purpose, it's a non-binding request to reduce capacity() to size().

这篇关于std :: vector resize下来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆