简体   繁体   English

指向类的C ++排序数组

[英]C++ Sorting array that is a pointer to a class

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. 当我尝试更改数组的顺序时,出现“错误C2106:'=':左操作数必须为l值”。

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

getPrice() in defined to return a double: 定义中的getPrice()以返回双getPrice()

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): 现在,在下面的语句中,由于您试图给赋值一个数字(相对于变量),因此您将收到错误C2106:

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). 尝试在发生错误的地方使用std::swap (在汽车对象上)(需要定义move分配和构造函数)。

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). PS:之所以出错,是因为您的getter函数返回一个值而不是引用(您可以为其分配值)。

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 = . 如果您不想使用标准库,则可以让getter方法返回引用,也可以在=的左侧使用setter函数。

Problem: Given the class implementation, you cannot set the price using getPrice() since it is just a getter not a setter. 问题:给定类的实现,您不能使用getPrice()设置价格,因为它只是一个获取器而不是一个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). 请回想一下它们是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. 您可以使用库排序(即std :: sort),它是“快速排序”的,并且对于大数据具有O(nxlogn)时间复杂性,因此速度要快得多。 You may refer to: 您可以参考:

http://www.cplusplus.com/reference/algorithm/sort/?kw=sort 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: (编辑:如n0rd所建议,而不是运算符重载,您可以为更通用的方法定义一个自定义比较器。在上面的链接中有一个示例操作。)您的最终类如下所示:

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: 最后,在您的sort函数中,只需调用:

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! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM