运算符在cpp中的struct内部重载 [英] Operator overloading inside struct in cpp

查看:202
本文介绍了运算符在cpp中的struct内部重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 最小生成树 - 具有不相交集合联盟的Kruskal - 具有竞争力编程算法 [ ^ ]我很困惑在上面实现中使用的下面的运算符重载部分,这里我们如何排序而不定义比较器。



如何在不定义任何比较器的情况下对两个结构进行排序,如何编译器知道它有两种排序?

当我们打算使用时e1< e2那么谁将调用运算符重载< pre> +< / pre>即e1或者e2。



假设STL的默认比较器使用类似的东西排序

< pre> e1< e2< / pre> (e1和e2是Edge类型)然后如何将参数传递给`bool operator<(Edge const& other)`在struct中。



我是什么尝试过:



I was reading Minimum spanning tree - Kruskal with Disjoint Set Union - Competitive Programming Algorithms[^] and I am confused in below operator overloading part used in above implementation,here how we can sort without defining the comparator.

How is sorting taking Place over two structure without defining any comparator,how compiler get to know on what basis it has two sort?
When we are going to use when e1<e2 then who will call the operator overloaded <pre>+</pre>that is e1 or e2.

suppose the default comparator of STL sort using something like this
<pre> e1<e2 </pre> (e1 and e2 are of Edge type) then how are parameters passed to `bool operator<(Edge const& other)` inside struct.

What I have tried:

struct Edge {
    int u, v, weight;
    bool operator<(Edge const& other) {
        return weight < other.weight;
    }
};
vector<Edge> edges;
sort(edges.begin(), edges.end());

推荐答案

运算符< 的定义允许sort方法比较两个 Edge 元素。 sort 调用从第一个到最后一个采用向量的元素,并使用结构中定义的重载比较器来决定应该保存它们的顺序。因为为Edge类型定义了小于运算符,这是在排序执行时使用的方法:

The definition of the operator < allows the sort method to compare two Edge elements. The sort call takes the elements of the vector from first to last, and uses the overloaded comparator as defined in the struct, to decide which order they should be saved in. Because the less than operator is defined for the Edge type, that is the method that will be used when sort does something like:
if (elem1 < elem2)
{
    // ...
}


Richard 已经给你正确的答案。



作为附录,查看文档 std: :sort - cppreference.com [ ^ ],注意使用 std :: sort 的第一个重载。



此外,阅读这篇文章:排序自定义矢量C ++中的对象 [ ^ ],可以很有帮助。
Richard already gave you the correct answer.

As an addendum, looking at the documentation std::sort - cppreference.com[^], note the first overload of std::sort is used.

Moreover, reading this article: "Sorting a vector of custom objects in C++"[^], could be helpful.


这篇关于运算符在cpp中的struct内部重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆