Reputation: 37
I have made paired vectors and I want to sort one vector according to the values of other vector, but when I run my program the vectors aren't getting sorted. They just remain the same. And I think it is because of the pair that I have made I have actually just copied the code to perform paired sorts from internet and replaced the arrays with vectors.
// Sort an array according to other using pair in STL.
// Function to sort vector b according to the order defined by vector a
void pairsort(vector<int> a, vector<int> b, int n)
{
pair<int, int> pairt[n];
// Storing the respective array
// elements in pairs.
for (int i = 0; i < n; i++)
{
pairt[i].first = a[i];
pairt[i].second = b[i];
}
// Sorting the pair array.
sort(pairt, pairt + n);
// Modifying original arrays
for (int i = 0; i < n; i++)
{
a[i] = pairt[i].first;
b[i] = pairt[i].second;
}
}
// Driver function
int main()
{
vector<int> a{60, 100, 120};
vector<int> c{3, 2, 4};
int n = sizeof(c) / sizeof(c[0]);
pairsort(c, a, n);
}
Upvotes: 2
Views: 73
Reputation: 75062
Copies of the original vectors are passed to the arguments vector<int> a
and vector<int> b
. Modifying the copies will not affect what are passed in caller.
Add &
after the types to make them references to reflect changes in the function to the caller.
Also Variable-Length Array like pair<int, int> pairt[n];
is not in the standard C++. You should use std::vector<pair<int, int> > pairt(n);
instead.
void pairsort(vector<int>& a, vector<int>& b, int n) // make a and be references
{
std::vector<pair<int, int> > pairt(n); // use std::vector instead of non-standard VLA
After making this change, this usage of sort
is wrong with std::vector
:
sort(pairt, pairt + n);
It should be:
sort(pairt.begin(), pairt.end());
One more point is that sizeof(c) / sizeof(c[0])
in the main()
function is not a correct way to retrieve the number of elements in the vector. It should be replaced with c.size()
.
Upvotes: 1