【问题标题】:Is this a bug in STL? Why do we need operator overloading in this Structure?这是 STL 中的错误吗?为什么我们需要在这个结构中重载运算符?
【发布时间】:2014-12-08 11:40:30
【问题描述】:

我遇到了 Equal_range 的这段代码,而且对 C++ 还是很陌生,我不清楚为什么我们需要重载运算符即使我们已经创建了一个新的比较函数

此外,我们可以使用:

bool compare( const S& s, const S& s2 )
{
    return s.number < s2.number;
}

改为。

#include <algorithm>
#include <vector>
#include <iostream>

struct S
{
    int number;
    char name;

    S ( int number, char name  )
        : number ( number ), name ( name )
    {}

    // only the number is relevant with this comparison
    bool operator< ( const S& s ) const
    {
        return number < s.number;
    }
};

struct Comp
{
    bool operator() ( const S& s, int i )
    {
        return s.number < i;
    }

    bool operator() ( int i, const S& s )
    {
        return i < s.number;
    }
};

int main()
{
    // note: not ordered, only partitioned w.r.t. S defined below
    std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4,'G'}, {3,'F'} };

    auto p = std::equal_range(vec.begin(),vec.end(),2,Comp());

    for ( auto i = p.first; i != p.second; ++i )
        std::cout << i->name << ' ';
}

编辑:代码的链接是http://en.cppreference.com/w/cpp/algorithm/equal_range

【问题讨论】:

    标签: c++ stl operator-overloading


    【解决方案1】:

    我认为这是您的 STL 实现中的一个错误。 C++ standard 明确声明它不会调用 operator

    对于第一个版本,使用 operator第二次比较。两个元素 a 和 b 被认为是等价的 if (!(a

    “第一个版本”是指没有提供比较类的版本。 “第二”是指您使用的版本。

    我在 VS2013 上试过这个,但它甚至没有编译。错误是:

    错误 C2664: 'bool Comp::operator ()(const S &,int)' : 无法转换 参数 1 从 'S' 到 'int'

    不幸的是,该错误在 Microsoft 混淆的 STL 实现的深处。为什么会调用 operator()(const S&, int) 而不是 operator()(int, const S&) ?

    所以我认为 Visual Studio 的 STL 实现是错误的。如果你的编译器需要它,我认为它的 STL 也是错误的。我想知道他们是否从来没有测试过这个第三个参数与迭代器返回的类型不同的地方。

    我很想听听其他人对此的看法。

    【讨论】:

      【解决方案2】:

      在您的示例代码中,您的各种比较方法都做了不同的事情; operator&lt; 重载允许您将S 与另一个S 进行比较,而Comp 结构允许您将Sint 进行比较,反之亦然。

      如果您阅读了equal_range 的文档

      对于第一个版本,使用 operator

      您看到您需要能够同时做到a[n] &lt; a[i]comp(a[n], val),第一个将列表中的项目与列表中的其他项目进行比较,第二个能够将列表中的项目与equal_range 调用的 val 参数。因此,您需要运算符重载和比较方法。

      【讨论】:

      • 为什么不调用 comp 结构进行两个比较?为什么还要依赖operator
      • 这个答案是错误的。文档说不带比较器的重载使用operator&lt;,但在上面的代码中,对equal_range 的唯一调用显式传递了比较器并且不应使用运算符(如果是,请针对实施)。
      猜你喜欢
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多