Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector and its initialization pointer consistence

I give the following codes to illustrate my question, and you can them in http://cpp.sh/

// Example program
#include <iostream>
#include <string>
#include <vector>

int main()
{
  int *p;
  p = new int [10];
  for(int i=0; i<10; i++)
      p[i] = i;

  std::vector<int> vecArray(p,p+10);
  vecArray[3]=300;

  for(int i=0; i<10; i++)
      std::cout<<vecArray[i]<<std::endl;

    for(int i=0; i<10; i++)
      std::cout<<p[i]<<std::endl;

  delete []p;
}

From the codes we can see that after the pointer p is used to initialze the vector vecArray then when the content of the vector is changed it will not affact the content in the pointer. My question is: how could it be possible that content of the vctor is always the same with the pointer?

like image 536
feelfree Avatar asked Feb 01 '26 12:02

feelfree


1 Answers

The content of the vector is a copy of the content of your dynamically allocated array.

You need to understand that your sample code allocates 10 integers TWO times, one time when you explicitly call new and the other one when you construct your vector.

You can have both sharing the same memory by, for example, first building your vector and then getting a pointer to its data :

#include <iostream>
#include <vector>

int     main(void)
{
  std::vector<int> vecArray(10);

  for(int i=0; i<10; i++)
    vecArray[i] = i;

  const int* p = vecArray.data();

  vecArray[3]=300;

  for(int i=0; i<10; i++)
    std::cout<<vecArray[i]<<std::endl;

  for(int i=0; i<10; i++)
    std::cout<<p[i]<<std::endl;
}
like image 111
Drax Avatar answered Feb 03 '26 05:02

Drax