如果 std::vector 包含的元素大小增加,它是否必须调整大小? [英] Does std::vector have to resize if the elements it contains grow in size?

查看:44
本文介绍了如果 std::vector 包含的元素大小增加,它是否必须调整大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题太基本而无法在这里提出,我深表歉意;我一直在阅读一些关于 std::vector 的内容,我知道当大小达到容量时它必须调整大小.如果它包含的对象很大,这可能是一项昂贵的操作,因为它必须复制每个对象.

I apologize if this is too basic a question to ask here; I've been reading a bit about std::vector and I understand that it has to resize when the size reaches capacity. This can be an expensive operation if the objects it contains are large since it has to copy every one of them.

我的问题是:std::vector 如何处理它所包含的对象的实际大小增长?假设我初始化了一些

My question is: how does std::vector handle the actual size of the objects it contains growing? Suppose I initialize some

std::vector<Obj> vec(100);

并且每个 Obj 都被初始化为非常小的东西.但是如果我再做类似的事情

And each Obj is initialized to something very small. But what if I then do something like

vec[14].ENGORGIO()

所以它现在需要更多的内存.由于 std::vector 的元素存储在连续内存中,这是否意味着它必须调整大小(昂贵!)

So that it now takes much more memory. Since the elements of std::vector are stored in contiguous memory, does this mean that it has to resize (expensively!)

为了避免这种事情,我应该将指针存储在向量中而不是对象本身吗?像这样

To avoid this kind of thing, should I instead be storing pointers in a vector rather than the objects themselves? Like so

std::vector< std::unique_ptr<Obj> > vec;

谢谢

推荐答案

C++ 中数据类型的大小是在编译时设置的,不能更改.数据类型可能包含对其他对象的引用,这些其他对象的大小可能会有所不同,但引用的大小以及数据类型是不变的.

The size of a data type in C++ is set at compile time and cannot change. The data type may contain references to other objects, and these other objects can vary in size, but the size of the reference, and thus the data type, is unchanging.

考虑 vectorvector.内部 vector 可能包含 0 个元素或数十亿个元素,并且大小始终相同.外部 vector 只知道它包含 0 个或多个 vector ,而对内部 vector s 中包含的内容一无所知.

Consider a vector of vectors. The inner vector may contain 0 elements or billions and billions and it will always be the same size. The outer vector only knows that it contains 0 or more vectors and knows nothing about what is contained inside the inner vectors.

你不必担心这个.

这篇关于如果 std::vector 包含的元素大小增加,它是否必须调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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