vector及其初始化指针的一致性

std::vector and its initialization pointer consistence

本文关键字:一致性 指针 初始化 vector      更新时间:2023-10-16

我给出了以下代码来说明我的问题,您可以在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;
}

从代码中可以看出,使用指针p初始化向量vecArray后,当改变向量的内容时,不会影响指针中的内容。我的问题是:怎么可能vector的内容总是与指针相同?

vector的内容是动态分配数组内容的副本。

您需要了解示例代码分配10个整数两次,一次是在显式调用new时,另一次是在构造vector时。

你可以让两者共享相同的内存,例如,首先构建你的向量,然后获得指向它的数据的指针:

#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;
}

你可以让你的vector包含指向int的指针。

压入动态分配数组的向量地址。

#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;
  for(int i=0; i<10; i++)
      vecArray.push_back(&p[i]); //push_back addresses in the vector
  p[3]=300; //you can also: *(vecArray[3])=300;
  for(int i=0; i<10; i++)
      std::cout<<*vecArray[i]<<std::endl; // Deference your pointer to get the value
  for(int i=0; i<10; i++)
      std::cout<<p[i]<<std::endl;
  delete []p;
}

这是vector的构造函数,它使用范围

template <class InputIterator> vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());

下面是描述:

Range constructor: Constructs a container with as many elements as the range [first,last), with each element emplace-constructed from its corresponding element in that range, in the same order.

表示从对应的元素中取出mplace-constructed。这意味着它创建了一个由指针指向的对象的新副本。

这就是为什么The underlying type an std::vector uses must be CopyAssignable

作为summery vector,创建数组元素的拷贝集。所以如果你改变一个集合中的任何元素,它不会在另一个集合中反映出来。