GCC和Clang竖起大拇指 - Visual Studio旅行.逻辑错误?

Dei*_*Dei 0 c++ c++11

无法将其分解为一个较小的例子......所以我用一个std::multimap来存储一些值...这是一个简单的多项式类.

问题是最后一个函数,它将两个多项式相乘.当它们相乘时,它会产生一个带有多个项的多项式,这些项可以相加在一起(2x^2 + 3x^2 => 5x^2).

所以我尝试这样做,Visual Studio抱怨(Debug Assertion Failed! Expression: map/set iterator not dereferencable).经过测试并与Clang和GCC一起工作正常.此外,它在发布模式下与Visual Studio完美配合,所以我认为这可能是我的错误或逻辑上的错误!所以我的问题是:以下代码是否有效且正确?如果没有,我该如何改进呢?请不要过多评论其他部分.

#include <iostream>
#include <cstddef>
#include <map>
#include <iterator>
#include <initializer_list>

//DIRTY YET SO BEAUTIFUL HACK       //don't judge the macro :P
#define EXPAND_PACK(FUN) \
        using type = int[]; \
        type{ 0, ((FUN), void(), 0)... }

template<class T>
class polynomial
{
private:
    struct _custom_compare //for std::multimap to sort properly
    {
        bool operator()(const std::size_t& a, const std::size_t& b) const
        {
            return a > b;
        }
    };

private:
    std::multimap<std::size_t, T, _custom_compare> _data;

public:
    template<class... Args>
    polynomial(Args&&... pack)
    {
        std::size_t power = sizeof...(pack)-1;

        EXPAND_PACK(_data.emplace(power--, pack));
    }

    auto operator*(const polynomial &rhs) const { return _multiply(rhs); }

    friend std::ostream& operator<<(std::ostream& os, const polynomial& poly)
    {
        //implementation of this not important
    }

private:
    auto _multiply(polynomial rhs) const
    {
        polynomial lhs(*this);

        polynomial<decltype((*_data.cbegin()).second + (*rhs._data.cbegin()).second)> ret;

        for (const auto& i : lhs._data)
        {
            for (const auto& j : rhs._data)
                ret._data.emplace(i.first + j.first, i.second * j.second);
        }

        decltype(ret) new_ret;
        std::size_t power = (*ret._data.cbegin()).first;

        decltype((*ret._data.cbegin()).second + (*ret._data.begin()).second) sum = 0;

        //POINT OF INTEREST HERE!!
        for (auto i = ret._data.cbegin(); i != ret._data.cend(); )
        {
            while ((*i).first == power)
            {
                sum += (*i).second;
                ++i;
            }

            new_ret._data.emplace(power, sum);
            sum = 0;
            --power;
        }

        return new_ret;
    }
};

int main()
{
    polynomial<int> p(3, 4);
    polynomial<int> p2(5, 8, 4);

    std::cout << p * p2;
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*eyA 5

你的代码有一个错误.

   while ((*i).first == power)
    {
        sum += (*i).second;
        ++i;
    }
Run Code Online (Sandbox Code Playgroud)

没有检查地图的边界.