繁体   English   中英

运算符在cpp中的结构中重载

[英]operator overloading in a struct in cpp

我正在阅读,在下面的运算符重载部分感到困惑,在这里我们如何在不定义比较器的情况下进行排序。

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

当我们要使用e1的时候

假设STL排序的默认比较器使用struct内部的类似e1bool运算符<(Edge const&other)的东西。

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

默认情况下, std::sort()使用operator<()作为比较器。 这就是为什么排序可以与Edge结构一起使用的原因。

如果您希望执行自定义排序,或者您的struct / class不提供operator<() ,则需要将比较器函数对象传递给std::sort() 例如,如果我们更改Edge结构以删除operator<() ...

struct Edge {
    int u, v, weight;
}; 

void print_edges(const std::vector<Edge> &edges)
{
    for (Edge const &e : edges)
    {
        std::cout << e.weight << std::endl;
    }
}


int main()
{
    std::vector<Edge> edges { {4, 5, 9}, {1, 2, 3} };
    std::cout << "Unsorted:\n";
    print_edges(edges);

    std::sort(edges.begin(), edges.end(), [](Edge const &lhs, Edge const &rhs){
        return lhs.weight < rhs.weight;
    });

    std::cout << "Sorted:\n";
    print_edges(edges);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM