我希望有一个向量z,并且能够以z[i]
或*pz[i]
访问它,其中*pz[i]
指向z[i]
。所以有一组值,但有两种方法可以访问它。
这是我的代码:
std::vector<double> z;
std::vector<double*> pz;
for (int i = 0; i < 5; i++) {
z.push_back(7+0.01*i);
std::cout << i << " z = " << z << std::endl;
pz.push_back(&z.back());
std::cout << i << " pz = " << pz << std::endl;
std::cout << i << " *pz = " ;
for (int j = 0; j < pz.size(); j++) {
std::cout << " " << *pz[j];
}
std::cout << std::endl;
}
z[1]=17.3;
std::cout << "z[1] = " << z[1] << std::endl;
std::cout << "*pz[1] = " << *pz[1] << std::endl;
*pz[2]=34.1;
std::cout << "z[2] = " << z[2] << std::endl;
std::cout << "*pz[2] = " << *pz[2] << std::endl;
输出:
0 z = vector(1) [ 7 ]
0 pz = vector(1) [ 0x1d00b80 ]
0 *pz = 7
1 z = vector(2) [ 7, 7.01 ]
1 pz = vector(2) [ 0x1d00b80, 0x1d00bc8 ]
1 *pz = 1.50254e-316 7.01
2 z = vector(3) [ 7, 7.01, 7.02 ]
2 pz = vector(3) [ 0x1d00b80, 0x1d00bc8, 0x1d00bf0 ]
2 *pz = 1.50254e-316 7.01 7.02
3 z = vector(4) [ 7, 7.01, 7.02, 7.03 ]
3 pz = vector(4) [ 0x1d00b80, 0x1d00bc8, 0x1d00bf0, 0x1d00bf8 ]
3 *pz = 1.50254e-316 7.01 7.02 7.03
4 z = vector(5) [ 7, 7.01, 7.02, 7.03, 7.04 ]
4 pz = vector(5) [ 0x1d00b80, 0x1d00bc8, 0x1d00bf0, 0x1d00bf8, 0x1d00c60 ]
4 *pz = 1.50254e-316 7.01 7.02 7.03 7.04
z[1] = 17.3
*pz[1] = 7.01
z[2] = 7.02
*pz[2] = 34.1
有3个问题:
*pz
的第一个元素未定义。z[1]
时,*pz[1]
不再是z[1]
。*pz[2]
时,它不再分配给z[2]
。(在我的实际程序中,我需要一个向量来访问偶数元素和一个向量来访问奇数元素,但我不想制作克隆并使用更多内存。)
答案 0 :(得分:7)
两件事:
push_back()
或任何可能导致向量重新分配的操作时,会使指向该向量元素的所有指针无效。double
的大小相同,因此您不会以这种方式保存任何内存。如果你真的想要创建第二个向量,指向第一个向量的元素,你需要先完成构建第一个向量。否则,push_back()
操作将使指针无效。
答案 1 :(得分:2)