I have two vectors
vector<string> names={"Raymond","Cynthia","David","William","Mike"}
, then I am doing a get_mark()
call on each student to get
vector<int> marks={50,80,45,25,90} .
Now I need to sort both vectors based on marks of student, i.e., result has to be
vector<int> marks_sorted ={25,45,50,80,90}
and
vector<string> names_sorted ={"William","David","Raymond","Cynthia","Mike"}
One method I can think is do sort of marks first then compare sorted and unsorted marks vector and then sort names, but is there an elegant way of doing this?
-Just adding one way of doing this for reference of someone else
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <algorithm>
using std::sort;
#include <string>
using std::string;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> data ;
data.push_back(5);
data.push_back(16);
data.push_back(4);
data.push_back(99);
vector<string> names ;
names.push_back("Crystal");
names.push_back("Bob");
names.push_back("Mynah");
names.push_back("TopNerd");
vector<int> index(data.size(), 0);
for (int i = 0 ; i != index.size() ; i++) {
index[i] = i;
}
sort(index.begin(), index.end(),
[&](const int& a, const int& b) {
return (data[a] < data[b]);
}
);
for (int i = 0 ; i != index.size() ; i++) {
cout << index[i] << endl;
}
for (int i = 0 ; i != index.size() ; i++) {
cout << data[index[i]] << endl;
}
for (int i = 0 ; i != index.size() ; i++) {
cout << names[index[i]] << endl;
}
getchar();
return 0;
}