我对C ++很新,我的问题可能听起来很愚蠢,但我正在使用向量处理排序函数。
代码能够编译并运行,但它不是排序。我可以知道原因吗?
missionplan.cpp
bool MissionPlan::sortByCiv(const PointTwoD &t1, const PointTwoD &t2)
{
return t1.locationdata.getCivIndex() > t2.locationdata.getCivIndex();
}
void MissionPlan::topfives()
{
topfive.assign( point1.begin(), point1.end() );
sort(topfive.begin(), topfive.end(), sortByCiv);
for(int i=0; i < 5; i++)
{
topfive.at(i).displayPointdata();
}
}
pointtwod.h
class PointTwoD
{
private:
int xcord,ycord;
float civIndex;
//LocationData locationdata;
public:
PointTwoD();
PointTwoD(int, int, float);
string toString();
void setPointDetail(int x, int y, float civ);
void displayPointdata();
void storedata(int, int, float);
//set/mutator function
void setxcord(int);
void setycord(int);
//get/accessor function
int getxcord();
int getycord();
float getcivIndex();
LocationData locationdata;
};
Locationdata.h
class LocationData
{
private:
string sunType;
int noOfEarthLikePlanets, noOfEarthLikeMoons;
float aveParticulateDensity, avePlasmaDensity;
static float civIndex;
public:
LocationData(); //default constructor
LocationData(string, int, int, float, float); // no default constructor
void setLocationData(string, int, int, float, float);
void displaydata();
string toString();
//'set' mustator function
void setsunType(string);
void setnoOfEarthLikePlanets(int);
void setnoOfEarthLikeMoons(int);
void setaveParticulateDensity(float);
void setavePlasmaDensity(float);
//'get' accessor function
string getsunType();
int getnoOfEarthLikePlanets();
int getnoOfEarthLikeMoons();
float getaveParticulateDensity();
float getavePlasmaDensity();
static float getCivIndex();
static float computeCivIndex(string st, int earth, int moons, float particle, float plasma);
};
我还有另外一个问题.. bool myfunction(int i,int j){return(i
我期待的结果
X: 4 Y: 9 CIV: 10
X: 1 Y: 2 CIV: 5
X: 5 Y: 4 CIV: 4
X: 6 Y: 1 CIV: 3
X: 10 Y: 6 CIV: 1
和我从我的编程收到的结果,它与我输入的方式完全相同。
X: 10 Y: 6 CIV: 1
X: 5 Y: 4 CIV: 4
X: 4 Y: 9 CIV: 10
X: 1 Y: 2 CIV: 5
X: 6 Y: 1 CIV: 3
X: 5 Y: 9 CIV: 8
答案 0 :(得分:2)
除非我严重错误地阅读您的代码,否则您调用错误的getCivIndex()
。您正在调用的是使用静态类变量。这意味着LocationData
的所有实例(包括PostTwoD
个对象中的内部实例)共享相同的静态变量,因此具有相同的相同值。换句话说,您的比较器总是返回 false ,因为N&gt; N永远不会是真的。因此,你的排序根本不起作用。
我相信您希望使用getcivIndex()
的{{1}}实例成员;不是PointTwoD
应该改变一些事情以使其“固定”
首先,改变一下:
LocationData
对此:(原因将在一分钟内显现)
float getcivIndex();
您还必须更改此函数的实现,无论在何处,都要将float getcivIndex() const;
添加到其定义中。
接下来,改变一下:
const
对此:
bool MissionPlan::sortByCiv(const PointTwoD &t1, const PointTwoD &t2)
{
return t1.locationdata.getCivIndex() > t2.locationdata.getCivIndex();
}
如果您想要的只是序列中的“前N个”结果,我建议您看到我关于使用bool MissionPlan::sortByCiv(const PointTwoD &t1, const PointTwoD &t2)
{
// use object instance-member. note: this is why getcivIndex()
// had to be made const. The t1 and t2 objects are const and as
// such only const-member-functions are callable.
return t1.getcivIndex() > t2.getcivIndex();
}
的评论,而不是完整的排序。