添加动态数组并删除尾随0

时间:2013-11-01 07:02:21

标签: c++ pointers

我正在尝试实现此功能以添加两个动态a rrays,但是当我把它实现到我的主要它完全崩溃时,我不知道为什么......

我无法理解为什么程序会关闭,除了scite上的退出代码说出口代码为255.但这没有用。知道问题可能是什么?

3 个答案:

答案 0 :(得分:1)

一个人:

for (int k=0; k<=max; k++)

这超出了范围。而是为[max+1]元素分配内存,因为多项式中应该有max+1个项

sum = new int[ max + 1 ];

此外,j循环应从max开始。

for (j=max; j>0 && sum[j]==0; --j);

答案 1 :(得分:1)

你在这一行上有一个错字:

for (j=max-1; j>0 && sum[j]==0; --j); 
                                    ^here

下一个语句int *tmp=sum;未执行。

for循环也应该是

for (j=max-1; j>=0 && sum[j]==0; --j)
                ^ //don't forget the last member

答案 2 :(得分:1)

关于C ++的一些好处是standard containers(如std::vector)和standard algorithms available。例如,您可以使用向量和向后迭代器以及std::find_if_not来查找最后一个非零值。

// Create a vector of a specific size, and initialize it
std::vector<int> sum(std::max(a->degree, b->degree), 0);

// Fill it up...

// Find the last non-zero value
auto last_non_zero = std::find_if_not(sum.rbegin(), sum.rend(),
    [](const int& value){ return value == 0; });

if (last_non_zero == sum.rbegin())
{
    // No zeroes found
}
else if (last_non_zero == sum.rend())
{
    // All of it was zero
    sum.clear();
}
else
{
    std::vector<int> temp(last_non_zero, sum.rend())
    std::reverse(temp);  // Because the `temp` vector is reversed
    sum = temp;
}

在此之后,矢量sum应该被剥去尾随零。

相关问题