I would like to have a vector z, and be able to access it as z[i] or *pz[i], where *pz[i] points to z[i]. so there is one set of values but two ways to access it.
This is the code that I had:
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;
the output:
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
There are 3 problems:
- The first element of
*pzgets undefined after second push. - When I assign
z[1],*pz[1]is notz[1]anymore. - When I assign
*pz[2], it’s not assigning toz[2]anymore.
(In my actual program I need to have a vector to access even elements and a vector to access odd elements but I don’t want to make a clone and use more memory.)
Two things:
push_back()or any operation that might cause the vector to be reallocated, you invalidate all pointers to elements of that vector.doubleso you won’t save any memory that way.If you really want to create a second vector with pointers to elements of the first vector, you need to finish building the first vector first. Otherwise, the
push_back()operations will invalidate the pointers.