vector及其初始化指针的一致性
std::vector and its initialization pointer consistence
我给出了以下代码来说明我的问题,您可以在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,创建数组元素的拷贝集。所以如果你改变一个集合中的任何元素,它不会在另一个集合中反映出来。
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- C++指针输出一致性
- vector及其初始化指针的一致性
- 如何在c++中实现与抽象类指针向量的缓存一致性
- 提供方法指针和派生类型对象时,std::bind的一致性