Vector of Pairs of References?

I am attempting to combine two vectors into a vector of pairs. I want to be able to alter the first and second of each pair and have those alterations reflected in the original vectors. I thought the following code might work but get compilation errors about a lack of viable overload for "=" for the line with the call to std::transform:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void f()
{
    std::vector<int> a = {1,2,3,4,5};
    std::vector<int> b = {6,7,8,9,0};
    std::vector<std::pair<int&, int&>> target;
    target.reserve(a.size());
    std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(target),
                   [](int& x, int& y) { return std::make_pair(x, y); });
    for(auto& each : target) {
        each.first--;
        each.second++;
    }
    for(auto& eachA : a) {
        std::cout << eachA << "\n";
    }
    for(auto& eachB : b) {
        std::cout << eachB << "\n";
    }
}

What have I missed?
I guess this is what std::reference_wrapper is for.
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
Last edited on
1
2
    std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(target),
        [](int& x, int& y) { return std::make_pair(std::ref(x), std::ref(y)); });


The problem is with type deduction in make_pair. You need to give it a little hint.

Thanks, You 2. That did it. :-) For the record, I have consistently found this site far more helpful than just about any other site. I'd like to think it's because of People like You. :-)
Topic archived. No new replies allowed.