-3

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;

}
vipin
  • 43
  • 1
  • 9

1 Answers1

0

An elegant way (in my opinion) of doing this would be as follows

#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 main() {

    vector<pair<string, int>> vector_of_students
        {{"Raymond", 1}, {"Cynthia", 80}, {"David", 85}};

    std::sort(vector_of_students.begin(), vector_of_students.end(),
            [](const std::pair<string, int>& p1, const std::pair<string, int>& p2) {
                return p1.second < p2.second;
            });

    // print the values out
    for (const auto& pa : vector_of_students) {
        cout << pa.first << '\t' << pa.second << endl;
    }

    return 0;
}

Here I used the sort method with a custom comparator, ask me if you need help understanding the syntax.

Curious
  • 20,870
  • 8
  • 61
  • 146