我正在尝试使用冒泡排序对城市列表及其温度进行排序

Im trying to sort a list of Cities and their Temperature using a bubblesort

我是 C++ 的新手,我正在尝试将一个整数“city.temp[4]”转换为一个字符串,然后将其添加到一个已经存在的字符串“city.name[4]”中然后将根据从低到高对城市及其温度进行排序。用户是为所有四个城市命名并为它们分配温度的人。 bubbleSort 可以很好地自行对温度进行排序,但我不确定如何让城市跟随它们各自的温度

#include <iostream>
using namespace std;

class City{
public:
    string name[4];
    int temp[4];

};
    
int main() {    
    City city;
    city.name[4];
    city.temp[4];
  
    cout << "           Please Input the name of 4 different cities and their temperature\n\n\n";

        for(int i=0; i < 4; i++){

            cout << " Input the name and temperature of city (" << i+1 << "): "; getline(cin, city.name[i]); cout << " "; cin >> city.temp[i];
            cin.ignore();    
        }
   
    int length = 4;

    for(int i = 0; i < length; i++){

        for(int j = 0; j < length - 1; j++){

            if(city.temp[j] > city.temp[j+1]){

                int hold = city.temp[j];
                city.temp[j] = city.temp[j+1];
                city.temp[j+1] = hold;
            }
        }
    }




    for(int i = 0; i < length; i++)

        cout << " " << city.temp[i] << " " << city.name[i] << "\n";
   
    return 0;
}

好的解决方案是让 City-class 具有名称和温度,并根据温度的顺序将城市与 std::sort 交换城市。

目前最简单的解决方法是使用 std::swap 交换温度,同时交换名称:

if(city.temp[j] > city.temp[j+1]){
    std::swap(city.temp[j], city.temp[j+1]);
    std::swap(city.name[j], city.name[j+1]);
}