Sorting three vectors simultaneously

I was trying to sort three vectors of equal size, Student_ID, Name, Age. Now the information is randomly stored but the corresponding elements have the same index, e.g, Student_ID[10], Name[10] and Age[10] belongs to the same person.
I want to sort Student_ID in ascending order and will have to sort Name and Age accordingly such that after sorting as also the same index of the vector corresponds to the same person. Also, I want to find maximum and minimum Student_ID, here is what I tried. But this code is giving unexpected output, also is there a simpler way of doing this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  for(int i=0;i<Student_ID.size()-1;i++){
for(int j=i+1;j<Student_ID.size();j++){
if(Student_ID[i]>Student_ID[j]){
int a = Student_ID[i];
Student_ID[i]=Student_ID[j];
Student_ID[j]=a;

string b=Name[i];
Name[i]=Name[j];
Name[j]=b;

int c=Age[i];
Age[i]=Age[j];
Age[j]=c;
}
}
}
int min_ID = Student_ID[0];
int siz = Student_ID.size();
int max_ID = Student_ID[siz];

Instead of 3 parallel vectors you should use one vector of structs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student {
    int id;
    string name;
    int age;
    Student(int i, string n, int a) : id(i), name(n), age(a) {}
};

ostream& operator<<(ostream& os, const Student& s) {
    return os << s.id << ", " << s.name << ", " << s.age << '\n';
}

int main() {
    vector<Student> s;
    s.push_back(Student(7, "bob", 20));
    s.push_back(Student(3, "joe", 21));
    s.push_back(Student(9, "sue", 22));

    for (const auto &x: s) cout << x; cout << '\n';

    sort(s.begin(), s.end(),
         [](Student& a, Student& b){return a.id < b.id;});    

    for (const auto &x: s) cout << x; cout << '\n';
    
    cout << "Min id: " << s[0].id << '\n';
    cout << "Max id: " << s.back().id << '\n';
                    // or s[s.size()-1].id
}

Thanks, it works.
Topic archived. No new replies allowed.