我有一个 Edge 类定义如下
class Edge {
public:
//constructors & destructors
Edge();
Edge(const Edge& orig);
virtual ~Edge();
Edge(unsigned const int, const string&, const string&);
//getters & setters
unsigned int GetCost() const {return cost;}
//member functions
bool operator<(const Edge*) const;
private:
unsigned int cost; //cost of the edge
string cities[2]; //cities that the edge connect
};
//cpp file
bool Edge::operator<(const Edge* e) const {
cout << "edge" << endl; //function is never invoked
return this->cost < e->GetCost();
}
我想将这些边缘(最初包含在向量中)保留在 Edge* 集中,main() 中的相应代码是:
set<Edge*> edge_set;
vector<Edge*> edges;
print_vector(edges);
srand((unsigned)time(NULL));
while(edge_set.size() < K){ //randomly pick K edges that will form the tree
edge_set.insert(edges[rand()%edges.size()]);
}
print_set(edge_set);
我得到输出:
Edge vector:
edges[0] cost = 136
edges[1] cost = 558
edges[2] cost = 872
edges[3] cost = 1615
edges[4] cost = 654
edges[5] cost = 994
.
.
.
Edge set:
858
1242
436
636
804
我也尝试<
在 main 中定义一个用于重载运算符的函数,但我也无法设法让这个集合以这种方式排序,即无法<
调用重载的运算符。另请注意,我使用不同类型的参数(引用、指针、对象本身)进行重载<
。
我在这里做错了什么?我该如何解决这个问题?