Reputation: 3278
Suppose I have two vectors "a" and "b" and I want to sort "a", and I want "b" to be re-ordered just like the sorted "a".
The most logical approach I can think of is combining these two vectors into a single vector of std::pair so I can apply std::sort, below is a toy example
std::vector<int> a(3,1);
std::vector<std::string> b(3,"hi");
std::vector<std::pair<int,std::string>> p(3);
for(int i=0;i<a.size();i++){
p.push_back(std::make_pair(std::ref(a[i]),std::ref(b[i])));
}
p[0].first = p[0].first+1;
std::cout << p[0].first << " " << a[0] << std::endl;
I am expecting it to print 2 2 but it is printing 2 1. I also attempted replacing the for loop with
for(int i=0;i<a.size();i++){
p[i].first = std::ref(a[i]);
p[i].second = std::ref(b[i]);
}
but it is still printing 2 1. I could copy the values from "p" back to "a" and "b" after sorting but this will be inefficient when "a" and "b" is large. What am I doing wrong?
My compiler is gcc 4.9.3.
Upvotes: 2
Views: 2650
Reputation: 13988
You want a vector of pairs of references there like:
#include <iostream>
#include <string>
#include <vector>
#include <utility>
int main() {
std::vector<int> a(3,1);
std::vector<std::string> b(3,"hi");
std::vector<std::pair<int&, std::string&>> p;
for(int i=0;i<a.size();i++){
p.push_back(std::pair<int&, std::string&>(a[i],b[i]));
}
p[0].first = p[0].first+1;
std::cout << p[0].first << " " << a[0] << std::endl;
}
Beware though not every possible operation can be done with pair of references. E.g. you cannot create an instance of it by parameterless constructor. This is why you cannot initialize the vector with three empty elements as in your example:
std::vector<std::pair<int&, std::string&>> p(3);
Upvotes: 2