gpt4 book ai didi

c++ - GCC 和 Clang 竖起大拇指 - Visual Studio 之旅。逻辑错误?

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:51 25 4
gpt4 key购买 nike

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

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

所以我尝试这样做,Visual Studio 提示 (Debug Assertion Failed! Expression: map/set iterator not dereferencable)。在 Clang 和 GCC 上测试并运行良好。此外,它在 Release模式下与 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;
}

最佳答案

你的代码有一个错误。

   while ((*i).first == power)
{
sum += (*i).second;
++i;
}

不检查 map 的边界。

关于c++ - GCC 和 Clang 竖起大拇指 - Visual Studio 之旅。逻辑错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com