is std::vector same as array[number]? [duplicate]

∥☆過路亽.° 提交于 2020-01-14 18:50:08

问题


Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?

does std::vector always contain the data in sequential memory addresses as array[number]?


回答1:


For all types except bool, the standard requires the elements are contiguous in memory:

23.2.4/1 ... The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()

Do keep in mind that std::vector<bool> has special requirements and is not the same as an array of bool.




回答2:


Yes. Given:

std::vector<int> arr;

you can be sure that

&arr[0]

will give you a pointer to a contiguous array of ints that can (for instance) be passed legacy APIs.




回答3:


Yes. It does not, however, allocate on the stack.




回答4:


Yes, the vector use sequential memory for all the elements stored. That means random access is almost as fast as normal array's index.

But vector allocate its memory in heap instead of stack. So it could be less less efficient in some cases.




回答5:


When you use the standard allocator, you can be sure that the allocated memory is continuous when using std::vector. In other words, foo[n+1] is the next element in the sequence after foo[n]. But std::vector is not an array, just like

int* blah = new int[100];

is not an array. But

int blah[100];

made on the stack is an array. Pointers to allocated memory and arrays just happen to share semantics. They are not equal per the standard, so don't confuse the two.



来源:https://stackoverflow.com/questions/3077748/is-stdvector-same-as-arraynumber

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!