c++for-loopranged-loops

Fill a vector of pointers with a range-based for loop


This code that fills a vector of pointers with the addresses of the elements of vector v works fine:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v{ 1,2,3,4,5 };
    vector<int*> pv;
    for (unsigned int i = 0; i < size(v); i++)
        pv.push_back(&(v[i]));
    for (auto i : pv)
        cout << i << " ";
    cout << endl;
    return 0;
}

How would I achieve the same result with a range-based for loop. I've tried code like this but it won't fill the vector of pointers correctly:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v{ 1,2,3,4,5 };
    vector<int*> pv;
    for (auto i : v)
        pv.push_back(&i);
    for (auto i : pv)
        cout << i << " ";
    cout << endl;
}

I'm sure I have something quite simple wrong - but haven't been able to work it out after searching around a bit. Thanks everyone!


Solution

  • Take the elements by reference:

    for (auto& r : v)
        pv.push_back(&r);
    

    Your original range-based for loop iterates the vector by value, making each i a fresh copy of each item. The expression &i therefore does not retrieve the address of element inside v.

    Iterating by reference, each r refers to the very element inside v, and thus the address-of expression &r correctly retrieve the element's address.