【问题标题】:C++ Sorting array that is a pointer to a classC ++排序数组是指向类的指针
【发布时间】:2015-06-11 08:53:10
【问题描述】:

我正在尝试对包含价格的汽车数组进行排序,我似乎在对指向另一个类的指针的数组进行排序时遇到问题。当我尝试更改数组的顺序时,我得到“错误 C2106:'=':左操作数必须是左值”。

我附上了下面的代码。

我的排序功能。

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

汽车.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!
}

汽车.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 代替数组。当您使用标准库函数时,您的代码往往会更简单、更快且更无错误。

标签: c++ arrays class sorting pointers


【解决方案1】:

getPrice() 定义为返回双精度:

double Car::getPrice()

现在,在以下语句中,您会得到 ERROR C2106,因为您尝试将分配赋值为数字(相对于变量):

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

【讨论】:

    【解决方案2】:

    尝试使用std::swap(在汽车对象上)出现错误(您需要定义move 赋值和构造函数)。

    标准库为您实现了它 - 现在去使用它。

    PS:您收到错误是因为您的 getter 函数返回一个值而不是一个引用(您可以为其分配一个值)。

    如果您不想使用标准库,您可以让 getter 方法返回一个引用,或者您可以使用 = 左侧的 setter 函数。

    【讨论】:

      【解决方案3】:

      问题: 鉴于类实现,您不能使用 getPrice() 设置价格,因为它只是一个 getter 而不是 setter。因此行:

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

      预计会给出等式左侧的错误。

      解决方案: 你需要一个二传手。比如:

      ptrToPool[i].setPrice(someValue);
      

      示例实施: 尝试将以下方法添加到您的类中:

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

      然后调用这个方法来更新价格如下(用那些替换你的两行):

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

      补充: 尽管这将解决您当前关于错误消息的问题,但您仍然需要修改排序算法。

      1. 您要对汽车进行分类还是只对价格进行分类?仅供参考:交换价格不会影响其他数据!
      2. 您要实现哪种排序算法?插入排序还是选择排序?请记住,它们是 O(nxn)。您可以使用库排序(即std::sort),它是“快速排序”并且对于大数据而言具有更快的O(nxlogn)时间复杂度。您可以参考:

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

      编辑排序:

      要按价格升序对汽车进行排序,您可以执行以下操作:

      首先,使用库排序包括以下内容:

      #include <algorithm>
      

      其次,根据价格向您的汽车类添加小于 (

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

      最后在你的排序函数中调用:

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

      因此,您的最终排序函数将如下所示(是的,很短!):

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

      只需将此函数替换为您的排序函数,它就会根据汽车的价格按升序对汽车进行排序。

      希望有帮助!

      【讨论】:

      • 我仍然不确定如何对汽车进行分类,而不仅仅是价格。我是否必须为所有数据成员创建一个 setter 方法? @erol 耶尼亚拉斯
      • @BeginnerLK:因为您的问题是“对包含价格的汽车数组进行排序”。因此,我假设您想根据价格对汽车进行分类。不是吗?
      • @BeginnerLK:您必须为要在类植入之外单独修改的每个私有数据成员创建 setter 方法。在这里,我再次假设 ModelName、Registration、EngineSize 和 Price 都是您的 car.h 文件中您的类的私有数据成员,并且该类与任何其他类没有继承关系。
      • @BeginnerLK:如果你不介意的话,你能把你的汽车类的定义(我想是car.h)放在你的问题上吗?
      • 我已将 car.h 添加为问题的一部分。我现在更好地理解了课程是如何运作的。谢谢。 @erol 耶尼亚拉斯
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2013-04-19
      • 2023-03-11
      相关资源
      最近更新 更多