我有一个代码,我正在绘制不同的Shape,现在可以优先选择哪一个首先绘制方形,矩形和三角形。我已经覆盖了“<” (少于基类Shape的运算符。我对绘图的偏好按照在typeOrderTable中提到的递增顺序。因此三角形将在Square之前绘制但在编译时我得到错误错误:'class std :: vector'没有名为'的成员'排序'。
#include <iostream>
#include <vector>
#include <typeinfo>
#include <string.h>
using namespace std;
class Shape
{
public:
virtual void Draw() const = 0;
virtual bool Precedes(const Shape&) const ;
bool operator<(const Shape& s)
{
return Precedes(s);
}
private:
static char* typeOrderTable[];
};
char* Shape::typeOrderTable[] = {"Rectangle","Square","Triangle",0 };
bool Shape::Precedes(const Shape& s) const
{
const char* thisType = typeid(*this).name();
const char* argType = typeid(s).name();
bool done = false; int thisOrd = -1;
int argOrd = -1;
for (int i=0; !done; i++)
{
const char* tableEntry = typeOrderTable[i];
if (tableEntry != 0)
{
if (strcmp(tableEntry, thisType) == 0)
thisOrd = i;
if (strcmp(tableEntry, argType) == 0)
argOrd = i;
if ((argOrd > 0) && (thisOrd > 0))
done = true;
}
else // table entry == 0
done = true;
}
return thisOrd < argOrd;
}
class Square : public Shape
{
public:
virtual void Draw() const
{
std::cout << "Inside Draw of Square \n" ;
}
};
class Rectangle : public Shape
{
public:
virtual void Draw() const
{
std::cout << "Inside Draw of Rectangle \n" ;
}
};
class Triangle : public Shape
{
public:
virtual void Draw() const
{
std::cout << "Inside Draw of Triangle \n" ;
}
};
void DrawAllShapes(std::vector<Shape*>& list)
{
std::vector<Shape*> orderedList = list;
orderedList.sort();
std::vector<Shape*>::iterator it =orderedList.begin();
for (;it!=orderedList.end(); ++it)
(*it)->Draw();
}
int main()
{
std::vector<Shape*> vec;
vec.push_back(new Triangle);
vec.push_back(new Square);
vec.push_back(new Rectangle);
vec.push_back(new Square);
DrawAllShapes(vec);
return 0;
}
答案 0 :(得分:2)
没有std::vector<...>::sort
。相反,您需要使用std::sort
:
std::sort(orderedList.begin(), orderedList.end());
然而,这会尝试比较std::vector<Shape*>
中的指针(提示:如果可能的话,重构这个)。相反,您需要传递一个自定义比较器来取消引用指针:
std::sort(
orderedList.begin(),
orderedList.end(),
[](Shape *a, Shape *b) { return *a < *b; }
);