为什么这组自定义对象没有根据重载的操作器<进行排序

Why isn't this set of custom objects constructed sorted according to overloaded opreator <

本文关键字:lt 操作器 排序 重载 自定义 对象 有根据 为什么      更新时间:2023-10-16

我有一个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();
}

我想保持这些边(最初包含在一个向量)在边缘*集,并从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中定义一个重载<操作符的函数,但我也无法设法以这种方式排序这个集合,即无法调用重载的<操作符。还要注意,重载<需要使用不同类型的参数(引用、指针、对象本身)。

我在这里做错了什么?我如何解决这个问题?

两个指针都需要operator <。因为它是不真实的语言规则和你的操作符是对象和指针-默认的一个(std::less<Edge*>)将被使用。你可以存储对象,或者你可以编写你的functor,它将与指针一起工作并使用它(set对象应该像std::set<Edge*, Functor>一样声明)。

这样的

struct CompareCost : public std::binary_function<const Edge*, const Edge*, bool>
{
   result_type operator () (first_argument_type f, second_argument_type s)
   {
      return f->operator <(s);
   }
};
std::set<Edge*, CompareCost> edge_set;