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

Time:05-24

Im fairly new to C and im trying to convert an int "city.temp[4]" to a string and then adding that to an already existing string "city.name[4]" which would then sort the cities and their temperatures based on low to high. The user is the one to name all four cities and assign them a temperature. The bubbleSort is working fine sorting the temperatures by them self but im not sure how to get the cities to follow along with their respective temperatures

#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;
}

CodePudding user response:

The good solution is to have a City-class with a name and a temperature and swap cities based on the order of the temperature with std::sort.

The easy fix for now is to use std::swap to swap the temperatures and at the same time swap the names:

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]);
}
  •  Tags:  
  • c
  • Related