C ++如何排序数组变量 [英] C++ how to sort an array variable
问题描述
我有一个父类调用
Shape
Shape有两个子呼叫
Shape got 2 child call
Square and Rectangle
Shape类有一个变量调用区,它是int类型
Shape class got a variable call area, which is of int type
所以我创建了一个对象Square,Rectangle像这样
So i created some object of Square, Rectangle like this
int main()
{
Shape *shaped[100];
//then i did some adding of object..
int areaValue;
areaValue=1;
shaped[0] = new Rectangle();
shaped[0]->setArea(areaValue);
areaValue=7;
shaped[1] = new Square();
shaped[1]->setArea(areaValue);
areaValue=5;
shaped[2] = new Square();
shaped[2]->setArea(areaValue);
shapeCounter = 3;
sort(shaped[0],shaped[2]);
for (int i=0;i<shapeCounter;i++)
{
cout << shaped[i].getArea() << endl;
}
}
我尝试按升序区但它不工作。
I try to sort by ascending area but it doesnt work. no position change, the area still in the same sequence.
感谢您的帮助!
更新:
我在Shape.cpp中进行了以下更改
I did the following changes at Shape.cpp
bool Shape::orderByArea(const Shape* lhs, const shape* rhs)
{
return lhs->area() < rhs->area();
}
然后在main.cpp我做了
Then at main.cpp I did this
std::sort(shaped, shaped + 3, orderByArea);
但是我得到一个错误,orderByArea未在此范围内声明。
however i get an error, orderByArea was not declared in this scope.
我尝试的另一件事是:
使用向量排序
Another thing i tried was: To sort using vector
在Shape.h
At Shape.h
public:
bool operator<const Shape& x) const
{
return area < x.area;
}
在main.cpp
vector<ShapeTwoD*> sortVector;
sortVector.clear();
sortVector.assign(shaped,shaped + shapeCounter);
sort(sortVector.begin(),sortVector.end());
for(int i=0;i<shapeCounter;i++)
{
cout << sortVector[i].toDisplay() << endl;
}
但是没有什么可以排序。我尝试做一个打印输出,它的位置是一样的。
But nothing seems sorted. I try do a printout its position is same.
更新:现在固定。排序是工作。非常感谢专家!
我有另一个问题是
Shape * shaped [100] ;
Shape *shaped[100];
如何复制
Shape *shaped[100];
到
vector<Shape> myVector;
而不是
vector<Shape*> myVector;
所以我可以使用正常的对象排序。
so i can use the normal object sort.
推荐答案
在你的代码中你是怎么期望编译器知道你想按区域排序,魔术?我建议读一本关于标准C ++库(又名STL)的书,它将解释如何做自定义排序。在你的代码中,你有一个指针数组,所以你应该写一个可以排序指针的函数。另外你的std :: sort的参数是错误的。你的数组从成形
开始,结束于 shaped + 3
(因为数组中有三个元素) / p>
In your code how did you expect the compiler to know that you wanted to sort by area, magic? I would recommend reading a book on the standard C++ library (aka the STL), it will explain how to do custom sorting. In your code you have an array of pointers, so you should write a functor that can order your pointers. Also your parameters to std::sort are wrong. Your array starts at shaped
, and ends at shaped + 3
(since you have three elements in your array).
struct sort_by_area
{
static bool operator()(Shape* x, Shape* y)
{
return x->getArea() < y->getArea();
}
};
sort(shaped, shaped + 3, sort_by_area());
未经测试的代码,表示任何错误。
Untested code, apologies for any mistakes.
或者你可以使用一个函数指针juanchopanza说。
Or you can use a function pointer as juanchopanza says.
这篇关于C ++如何排序数组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!