One question about vector push_back

I just noticed that for vector push_back this returns a reference to the element.

void push_back ( const T& x );

My question is: has the memory layout changed after push_back?

For example, I have the first array that contains five elements and the layout is as follows.

|          |          |          |          |          |              
|   A1     |     A2   |   A3     |    A4    |    A5    |

Now I have a vector v

v.push_back(A3)

Now, what does memory look like?

How does a vector store elements here?

How does a vector access an element?

+3
source share
4 answers

The vector is stored by value not by reference .

When you add the same item again, the copy will be saved at the end. If you do not want to copy the values ​​that you paste into vector, then you should use pointers.

Example:

std::vector<std::string> v;
string s = "";
v.push_back(s);
s = "hi";
v.push_back(s);

v 2 : , "hi". s.

. STL , , ; STL .

+6

, ? ?

:

  • , , . ( ) . push_back 'd ( ) .
  • , ( ) .

?

C-. BasePointer + index

+3

vector::push_back , , .

,

| A3 |

, , . , A1, A2,... A5 v,

v.push_back(A3)

will invalidate A3because it A3refers to the data inside v. The only way to keep the data descriptor inside the vector as it grows is to save the index; links, pointers and iterators will not do.

+2
source
|   A1     |     A2   |   A3     |    A4    |    A5    |   A3     |

Elements (like everything in STL) are stored by value.

Vectors have access elements similar to built-in arrays.

0
source

Source: https://habr.com/ru/post/1736420/


All Articles