0

I have the vectors:

vector<string> countriesName;
vector<long> countriesPop;

These contain data such as

countriesName = {"UK","GER","IRE"};
countriesPop = {561655,6518,5168};

I am trying to work out how to sort the countries population from smallest to largest while keeping the index's between the two vectors the same.

I have seen other solutions which require to use a struct and a vector of the structs. However as I have other functions which already rely on the original vectors I would preferably find a solution using these so I dont have to rework a lot of other functions.

Therefore the output after sorting should go from

UK 561655
GER 6518
IRE 5168  

To

IRE 5168
GER 6518
UK 561655
Roodolpha
  • 101
  • 1
  • 1
  • 12
  • 1
    You probably misunderstood the other solutions -- all that needs to be done is to create a separate vector of indexes, then sort that, and use the result to resort the original vectors. No need to change the structure of the existing vectors. – Sam Varshavchik Apr 26 '22 at 11:10
  • Hmmm. A vector of `struct`s would make more sense though, `countriesName` and `countriesPop` clearly belong together, and if you carry on as you are, things are likely to get messy (again) somewhere down the line. If it was me, I _would_ put them both into a struct (along with any other information pertaining to a country - more might come along later, don't you think?). – Paul Sanders Apr 26 '22 at 11:22
  • OK, that might have some knock-on effects, but if you bite the bullet now, your future self will thank you for it. One thing that might ease the pain is to add a couple of [conversion operators](https://en.cppreference.com/w/cpp/language/cast_operator) to that struct. Your existing code would probably then need fewer changes, although it's not really a good long-term solution because you would be, IMO, abusing those operators somewhat. And you can then sort that struct by passing a suitable comparison function to `std::sort` (people often use a lambda). – Paul Sanders Apr 26 '22 at 11:23

0 Answers0