Я пытаюсь сортировать массив автомобилей, у которых в них есть цены. Кажется, у меня проблема с сортировкой массива, который является указателем на другой класс. Я получаю «ошибка C2106: '=': левый операнд должен быть l-value», когда я пытаюсь изменить порядок массива.C++ Сортировка массива, который является указателем на класс
Приведенный ниже код.
Моя сортировка функция.
void CarPool::Sort()
{
const int MAXVAL = 9;
int coun = countCars;
double temp;
bool swappedFlag = true;
while (swappedFlag)
{
swappedFlag = false;
for (int i = 0; i < countCars - 1; i++)
{
ptrToPool[i].getPrice();
if (ptrToPool[i].getPrice()> ptrToPool[i + 1].getPrice())
{
temp = ptrToPool[i].getPrice();
ptrToPool[i].getPrice() = ptrToPool[i + 1].getPrice(); //ERROR C2106
ptrToPool[i + 1].getPrice() = temp; //ERROR C2106
swappedFlag = true;
}
}
}
}
car.cpp
#pragma once
#include "car.h" // put the related header at the TOP of the list of includes
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
Car::Car(string mName, string reg, double eng, double pri)
{
// store the parameter values for this object private data
ModelName = mName;
Registration = reg;
EngineSize = eng;
Price = pri;
}
Car::Car()
{
// set up a value that shows the data not properly loaded
ModelName = "Unspecified";
}
void Car::Load(ifstream& carFile)
{
carFile>>ModelName>>Registration>>EngineSize>>Price;
}
void Car::Display()
{
cout<<setfill(' ')<<setw(10)<<ModelName<<setfill(' ')<<setw(10)<<Registration;
cout<<setfill(' ')<<setw(10)<<EngineSize<<setfill(' ')<<setw(10)<<Price<<endl;
}
double Car::Ratio() //how much it costs per cc of engine!
{
return EngineSize/Price;
}
string Car::getRegistration()
{
return Registration;
}
double Car::getPrice()
{
return Price;
}
carpool.cpp (также функция, перечисленные в первой части кода)
#include "carpool.h"
#include <iostream>
#include <fstream>
using namespace std;
CarPool::CarPool()
{
countCars=0; //for now
name = "None";
}
CarPool::~CarPool()
{
if (countCars>0)
{
delete [] ptrToPool;
}
}
int CarPool::Load(string fromFilename)
{
// assumes file starts with count of cars
ifstream inFile(fromFilename);
if (!inFile)
{
return -1; //oh dear no file to read
}
inFile>>countCars; //read the following number of cars
ptrToPool = new Car[countCars];
for (int i=0; i<countCars; i++)
{
ptrToPool[i].Load(inFile);
}
return 0; //successful!
}
car.h
#pragma once
#include <string>
using namespace std;
class Car
{
public:
// see later for the bodies of the functions!
Car(string mName, string reg, double eng, double pri);
Car();
void Load(ifstream& carFile);
void Save(ofstream& carFile);
void Display();
string getRegistration();
double getPrice();
double Ratio(); //how much it costs per cc of engine!
void setPrice(double pri);
private:
string ModelName;
string Registration;
double EngineSize;
double Price;
};
Вам нужно поменять местами сами автомобили, а не значения. "ptrToPool [i] = ptrToPool [i + 1];" и т. д. Кроме того, я бы настоятельно рекомендовал использовать более стандартные библиотечные функции. В частности, std :: sort выполнил бы большую часть работы для вас. Вы также можете использовать std :: swap для свопа. Вы также можете использовать std :: vector вместо массива. Когда вы используете стандартные библиотечные функции, ваш код имеет тенденцию быть более простым, быстрым и более безаварийным. – Lalaland