[英]error: ‘class std::vector<Shape*>’ has no member named ‘sort’
I have a code where I am drawing different Shape , now there can be preference on which one to draw first among say Square, rectangle and triangle .我有一个代码,我在其中绘制了不同的 Shape ,现在可以优先选择在 Square、 rectangle 和 triangle 中首先绘制哪个。 I have override the "<" ( less than operator for base class Shape. My preference of drawing is in increasing order as mentioned in typeOrderTable. Therefore triangle will be drawn before Square But upon compilation I get the error error: 'class std::vector' has no member named 'sort'.
我已经覆盖了“<”(小于基类 Shape 的运算符。我对绘图的偏好是按 typeOrderTable 中提到的递增顺序。因此三角形将在 Square 之前绘制但在编译时我收到错误错误:'class std:: vector' 没有名为 'sort' 的成员。
#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;
}
There is no std::vector<...>::sort
.没有
std::vector<...>::sort
。 Instead, you will need to use std::sort
:相反,您需要使用
std::sort
:
std::sort(orderedList.begin(), orderedList.end());
However , this will try to compare the pointers in your std::vector<Shape*>
(hint: refactor this if at all possible).但是,这将尝试比较
std::vector<Shape*>
的指针(提示:如果可能,请重构它)。 Instead, you will need to pass a custom comparator that dereferences the pointers:相反,您需要传递一个取消引用指针的自定义比较器:
std::sort(
orderedList.begin(),
orderedList.end(),
[](Shape *a, Shape *b) { return *a < *b; }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.