+ 1
How to sort several concatenated vectors in c++?
Hello world! ✌🏻 I have several vectors that contains different data type( eg country names, populatio etc) and I want to sort those vectors ( eg, sort countries by their population in decreasing order, I know how to sort population vectors, but I can figure out how can I connect population vector with country name vector, so they match each other) Thank you 🙏
5 Respuestas
+ 2
You can use algorithms from <algorithm> library , I'll post code , look how works it in decreasing order , how you wanted
And how to match , you can use input or with cycles to match together)
+ 2
I would use a map if you only have country and population.
+ 2
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(pair<string, int> p1, pair<string, int> p2){
return p1.second > p2.second;
}
int main(){
vector<pair<string, int>> countries = {{"Russia", 145},{"USA", 360}};
sort(countries.begin(), countries.end(), cmp);
for(int i=0; i<countries.size(); ++i){
cout << countries[i].first << " " << countries[i].second << endl;
}
return 0;
}
You can use pairs and sort it by your own comparator function. That is easier than using two vectors
0
Input data manually