I have the following task: you need to rewrite some of the elements of one container to another (in the example, everything is rewritten, but this is an example). In the example, for simplicity, int, but in my code there are quite voluminous objects, and, of course, I would like to write pointers to the receiver container, rather than rewrite the contents (the original container will not change while the receiver container is in operation, so the pointers will workers).
#include <iostream> #include <vector> class Test { public: std::vector<int> testvector = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; std::vector<int*> ptrvector; void testmethod() { for(auto i:testvector) ptrvector.push_back(&i); for(auto i:ptrvector) std::cout << *i << std::endl; } }; int main() { Test test; test.testmethod(); return 0; }
This code will print zeros instead of the entire number series. This line is of course erroneous ptrvector.push_back (& i), because Here the address of the iterator is written, and not the object from the vector.
How do i get a pointer through iterator i?
&i
is not the address of the iterator, but the address of a temporary variable to which the array element is copied. - VladD