首页 文章

upper_bound使用binary_function Visual Studio 2008 Bug?

提问于
浏览
2

首先,是的,我被困在使用Visual Studio 2008,我相信这个bug是特定于Visual Studio 2008的 .

我正在尝试编写一个仿函数来比较我的结构中的1个成员,这样我就可以在 upper_bound 上对所述结构进行 upper_bound 的排序 . 那是's hard to explain in words so here'的一个例子:

struct Foo {
    int a;
    char b;
};

struct comp : binary_function<const double, const Foo&, bool> {
    bool operator () (const double lhs, const Foo& rhs) { return lhs < rhs.a; }
};

int main() {
    vector<Foo> test;

    for(int i = 0; i < 5; ++i) {
        Foo foo = { i + 1, 'a' + i };

        test.push_back(foo);
    }

    cout << upper_bound(test.begin(), test.end(), 2, comp())->b << endl;
}

这在Visual Studio 2015上工作正常 . 但是Visual Studio 2008给了我错误:

错误C2664:'bool comp :: operator()(const double,const Foo&)':无法将参数1从'Foo'转换为'const double'

我怀疑在实现中存在一些邪恶,其中函数通过交换输入来测试严格的弱排序 . 是否有一个解决方法来暂停对编译器的检查,或者我只需要将我的仿函数更改为接收2 Foo 并使临时 Foo 代表2在这里?

2 回答

  • 1

    stated by Algirdas Preidžius这是Visual Studio 2008中的仅调试实现错误 . 它已在visual-studio-2010上更正 .

    该错误是由_HAS_ITERATOR_DEBUGGING封闭的,因此如果禁用该选项,请考虑将"_HAS_ITERATOR_DEBUGGING=0"添加到"Preprocessor Definitions" .

    如果您不需要通过禁用 _HAS_ITERATOR_DEBUGGING 来解决方法,那么您的代码将类似于:

    struct Foo {
        int a;
        char b;
    };
    
    int main() {
        vector<Foo> test;
    
        for(int i = 0; i < 5; ++i) {
            Foo foo = { i + 1, 'a' + i };
    
            test.push_back(foo);
        }
    
    #if _HAS_ITERATOR_DEBUGGING
        for(vector<Foo>::const_iterator it = test.begin(); it != test.end(); ++it) {
            if(it->a > 2) {
                cout << it->b << endl;
                break;
            }
        }
    #else
        struct comp : public binary_function<const double, const Foo&, bool> {
            bool operator () (const double lhs, const Foo& rhs) { return lhs < rhs.a; }
        };
    
        cout << upper_bound(test.begin(), test.end(), 2, comp())->b << endl;
    #endif
    }
    

    这里有几个笔记:

    • 请注意,我正在使用 #if ,这意味着 if -block只有在定义 _HAS_ITERATOR_DEBUGGING 且非0时才会执行 . 在设计时,Visual Studio 2008似乎总是认为它是未定义的

    • 我的代码定义 comp 内联如果您的特定情况需要 comp 来在多个地方使用首先考虑将整个 else -block包装在一个函数中以限制代码中 #define 的数量,显然此注释的适用性将受到限制,如果你在多种标准算法中使用 comp

  • -1

    正如Algirdas Preidžius所提到的,这是因为strict weak orderings检查 .

    作为一种解决方法,您可以定义两个运算符 .

    struct comp {
        bool operator () (const double lhs, const Foo& rhs) { return lhs < rhs.a; }
        bool operator () (const Foo& lhs, const double rhs) { return lhs.a < rhs; }
    };
    

相关问题