如何设置stl :: vector的初始大小? [英] How to set initial size of stl:: vector?

查看:394
本文介绍了如何设置stl :: vector的初始大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有向量< CustomClass *> 和我把很多项目在向量中,我需要快速访问,所以我不使用列表。如何设置向量的初始大小(例如,要20 000个位置,以避免在插入新的时候复制)?

I have vector<CustomClass*> and I put lot off items in vector and I need fast access, so I don't use list. How to set initial size of vector (for example to be 20 000 places, so to avoid copy when I insert new ) ?

推荐答案

std::vector<CustomClass *> whatever(20000);

或:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

前者设置数组的实际大小,即使它成为一个20000指针的向量。后者使向量为空,但为20000个指针保留空间,因此您可以插入(多达)许多而不必重新分配。

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

你应该知道这种做任何真正的好处的机会是最小的,虽然。

You should probably be aware that chances of this doing any real good are minimal though.

这篇关于如何设置stl :: vector的初始大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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