都市の名前(char型)、幅(double)、長さ(double)、高さ(double)シティ。私は動的な配列を作成する必要があります。これは、プログラムが起動するときに、デフォルトでCity()によって挿入されます。プログラムはメソッドoutput()を使用して、cities.mAの配列を挿入します。ソートを長さでソートする。私はコピーコンストラクタ、operator =を持っていて、都市を入力するためにダブルマックス(これは変数、現在の最大値を格納するバブルソートで使用される)を変換しなければならず、この目的でコンストラクタをパラメータ:City(double max)。問題はソートが機能しないことです。私は問題が1つのパラメータを持つコンストラクタの定義にあると思う(タイプdoubleをタイプ都市に変換する)。 {;手動仕分けC++でオブジェクトの動的配列をソートするのにバブルソートが機能しない
#include "stdafx.h"
#include<iostream>
#include<math.h>
#include <algorithm>
using namespace std;
class City{
private: char *name;
double width;
double length;
double height;
public:
void Output();
City();
~City();
City(double max){
name = "";
width = 0;
length = max;
height = 0;
}
double GetLength()
{
return length;
}
double GetWidth(){ return width; }
double GetHeight(){ return height; }
char GetName(){ return *name; }
City(const City& that)
{
name = new char[strlen(that.name) + 1];
for (int i = 0; i <= strlen(that.name); i++)
name[i] = that.name[i];
//strcpy(name, that.name);
width = that.width;
length = that.length;
height = that.height;
}
City& operator=(const City that)
{
name = that.name;
width = that.width;
length = that.length;
height = that.height;
return*this;
}
};
City::City()
{
char ime[20];
cout << "Name= ";
cin >> ime;
name = new char[strlen(ime) + 1];
for (int i = 0; i <= strlen(ime); i++)
name[i] = ime[i];
cout << "Width= ";
cin >> width;
cout << "Length= ";
cin >> length;
cout << "Height= ";
cin >> height;
}
void City::Output()
{
cout << "Name is: " << name << endl;
cout << " Width is: " << width << " deg" << endl;;
cout << " Length is: " << length << " deg" << endl;
cout << " Height is: " << height << " m" << endl;
return;
}
City::~City()
{
cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}
int main()
{
int n;
City *mA;
cout << "Input number of cities: " << endl;
cin >> n;
mA = new City[n];
for (int j = 0; j < n; j++)
{
mA[j].Output();
}
cout << "Cities from west to east, sorted by their length" << endl;
double max = mA[0].GetLength();
for (int j = 1; j<n; j++)
{
if (mA[j - 1].GetLength()>mA[j].GetLength())
{
max = mA[j - 1].GetLength();
mA[j - 1] = mA[j];
mA[j] = max;
}
}
for (int j = 0; j < n; j++)
{
mA[j].Output();
}
delete[]mA;
return 0;
}
「動作しません」はエラーの説明ではありません。あなたは何をするのですか?代わりに何をしますか? – SoronelHaetir
バブルソートには2つのネストされたループがあります。 – molbdnilo
値を入れ替えるには 'std :: swap'を使うべきです。今度はあなたの 'mA [j] = max;'は毎回 'max'から新しいオブジェクトを作成します(あなたが疑うコンストラクタを使って)。暗黙の変換を望まない場合は、 '明示的な都市(double max)'を作ることができます。 –