Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector vs dynamic array passing by value

Tags:

c++

vector

Hello I am comming from c to c++ and I've been wondering why can std::vector be passed by value.

I assume passing dynamicaly allocated array by value is not possible as that would only copy the pointer.

How is it then possible for a vector to be coppied, if inside of a vector class is same pointer. It has to somehow know how to reconstruct it into another object.

like image 579
Franta_B Avatar asked Jul 15 '20 19:07

Franta_B


People also ask

Is dynamic array faster than vector C++?

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.

Is vector faster than dynamic array?

It is highly unlikely that you'll see an appreciable performance difference between a dynamic array and a vector since the latter is essentially a very thin wrapper around the former. Also bear in mind that using a vector would be significantly less error-prone.

Is std :: array faster than vector?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

What is the difference between a C++ dynamic array vs vector?

Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface. Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.


1 Answers

std::vector knows how many elements are stored in the dynamic memory. It is a simple matter to allocate a new buffer of that size and copy the contents into that new memory. All of this happens in the copy constructor.

like image 182
jkb Avatar answered Oct 18 '22 23:10

jkb