【问题标题】:operator overloading in a struct in cppcpp结构中的运算符重载
【发布时间】:2019-03-08 09:33:54
【问题描述】:

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

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

当我们要使用e1的时候

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

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

【问题讨论】:

  • 这个真的不清楚你知道吗?请在关闭之前edit您的问题。请务必实际提出问题。另外,请阅读How to Ask
  • 这个问题还不清楚。 “我们如何在不定义比较器的情况下进行排序。”但你确实定义了一个比较器。正如您正确假设的那样,sort 默认使用operator&lt;。它读起来就像你回答自己的问题
  • 您是在问std::sort 的工作原理吗?

标签: c++ operator-overloading


【解决方案1】:

默认情况下,std::sort() 使用operator&lt;() 作为比较器。这就是为什么排序适用于您的 Edge 结构。

如果您希望执行自定义排序,或者您的结构/类不提供operator&lt;(),那么您需要将比较器函数对象传递给std::sort()。例如,如果我们将您的 Edge 结构更改为删除 operator&lt;()...

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;
}

【讨论】:

  • 你能告诉我上述算法中的排序是如何发生的吗?我的意思是你已经定义了自己的比较器,但他们在结构上做了一些事情?
  • @humblefool - 我更新了我的答案,以讨论 std::sort() 在没有自定义比较器的情况下如何工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多