为什么这组自定义对象没有根据重载的操作器<进行排序
Why isn't this set of custom objects constructed sorted according to overloaded opreator <
我有一个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;
相关文章:
- 迭代器的指针操作问题
- 使用双包装器类进行位操作(C++、clang)修复性能下降问题
- 为什么指针在由后增量比较器操作时行为不同?
- 打印矩阵后分割错误,但在打印额外行后修复(ostream <<操作器)
- 如何监控Android和iOS上的所有击键操作,如Windows键盘记录器
- 在模板上使用() - 操作器
- 操作器 [] 作为非静态函数
- 错误:如果(object1 == object2),“操作器==”无匹配(操作数类型为“ const class”和“
- 过载复合"+="操作器作为自由功能
- C# * 和 & 操作器,用于指向数组
- 方括号和圆括号操作器,如何选择重载
- 为什么C 流操作器没有呼叫操作员
- 如何使C++endl操作器线程安全
- LNK 2019 尝试重载"<<"操作器时出错
- 编译器不使用移动 c'tor / 赋值操作器?
- 使用新操作器创建多个对象
- 过载小于不同类型的操作器
- c++11的特定过载<<操作人员
- Visual Studio 编译和检测操作器重载,而 g++ 没有
- 为什么这组自定义对象没有根据重载的操作器<进行排序