c++/ arrays/ class/ sorting/ pointers

I am trying to sort an array of cars which have prices in them, I seem to be having a problem sorting the array that is a pointer to another class. I get "error C2106: '=' : left operand must be l-value" when I try to change the order of the array.

I have attached the code below.

My sort function.

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 (also the function listed in the first piece of code)

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

getPrice() in defined to return a double:

double Car::getPrice()

Now, in the following statements you get ERROR C2106 since you're trying to make an assignment a number (vs. a variable):

ptrToPool[i].getPrice() = ptrToPool[i + 1].getPrice(); //ERROR C2106
ptrToPool[i + 1].getPrice() = temp; //ERROR C2106

Try using std::swap (on the car objects) where you get the error (you need the move assignment and constructor to be defined).

The standard library implemented it for you - now go use it.

PS: You are getting the error because your getter function returns a value rather than a reference (to which you could assign a value).

If you don't want to use the Standard Library you could let the getter method return a reference or you could use a setter function on the left side of the = .

Problem: Given the class implementation, you cannot set the price using getPrice() since it is just a getter not a setter. Therefore the lines:

ptrToPool[i].getPrice() = ptrToPool[i + 1].getPrice(); //ERROR C2106
ptrToPool[i + 1].getPrice() = temp; //ERROR C2106

are expected to give error about the left hand side of the equation.

Solution: You need a setter. Something like:

ptrToPool[i].setPrice(someValue);

Sample Implementation: Try adding the following method to your class:

void Car::setPrice(double pri)
{
    Price=pri;
}

Then call this method to update prices as follows (replace your two lines with those):

ptrToPool[i].setPrice(ptrToPool[i + 1].getPrice());
ptrToPool[i + 1].getPrice(temp); 

Additional: Although this will solve your current issue on error messages, you still need to revise your sorting algorithm.

  1. Do you want to sort the cars or just prices? FYI: Swapping the prices will not affect the other data!
  2. What kind of sorting algorithm are you trying to implement? Insertion Sort or Selection sort? Please recall that they are O(nxn). You may use library sort (ie, std::sort) which is "quick sort" and has O(nxlogn) time complexity so much faster for large data. You may refer to:

http://www.cplusplus.com/reference/algorithm/sort/?kw=sort

EDIT ON SORTING:

For sorting the cars in increasing order of prices you could do the following:

First, include the following for using the library sort:

#include <algorithm>

Second, add a less than (<) operator overload to your car class based on price. (Edit: As n0rd suggested instead of operator overloading you may define a custom comparator for more generic approach. There is an example how to do in the above link.) You final class will look like:

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);
    bool operator < (const Car& car) const
    {
        return (Price < car.Price);
    }

private:
    string ModelName;
    string Registration;
    double EngineSize;
    double Price;
};

Finally in your sort function just call:

std::sort(ptrToPool, ptrToPool + size);

Therefore your final sort function will be the following (Yes that short!):

void CarPool::Sort()
{
    std::sort(ptrToPool, ptrToPool + countCars);
}

Just replace this function with your sort function and it should sort the cars based on their price in increasing order.

Hope that helps!

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question C++ Sorting Class Array Pointer Array Sorting Algorithm in C++ array of pointer in c++ class C++: declaring a pointer to an array within a class? Delete Inherited class Pointer Array in C++ C++ Polynomial Class, pointer array issue Destructor of class with pointer array C++ C++ dynamic array of pointer to another class Basic pointer to array of class for c++ C++ accessing class array pointer in a pointer to a structure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM