I am very curious why the following code compiles and yet does not produce a map of the expected values. I would expect the output to contain a vector of references to rows which can be accessed by an int from the row in column 2. In other words, I expected to map values in column two to their rows. However, any time something is added to the map, all of the pointers end up the same reference. Please let me know what the error is. Thanks very much.
On line 34, i is a copy of an element in *rows. On line 46, you add a pointer to that copy to a vector in the map. Each iteration of the loop, i will be a local copy of an element in *rows. Technically, that pointer is invalidated every iteration of the loop, so previous pointers to i inserted into the map are invalid and dereferencing them results in undefined behavior. Make line 34: for (auto& i : *rows)
(And get rid of your gratuitous use of new without a corresponding delete and the unnecessary pointers.)
Wow! Thank you! This has been puzzling me for so long!
Why on earth would a that loop return a local copy? I thought it would use iterators of rows or something along those lines.
(and the more than gratuitous use of new was done to mimic a larger project in which this bug came about)