为什么 C++ 中的矢量不会自动调整大小

Why vector in C++ doesn't resize automatically

本文关键字:调整 C++ 为什么      更新时间:2023-10-16

我有一个很长的阶乘程序,需要查找最高100的阶乘。它可以很好地工作33个阶乘,但从34中却不能。有人可以帮助识别问题。

#include <iostream>
#include <vector>
#include <utility>

using namespace std;
void bigFactorials(int n)
{
    vector<int> v;//If I specify the size as v(1000) it works fine but I don't 
    //want to specify the size beforehand.
    v.push_back(1);
    // Complete this function
    for(int i=2;i<=n;i++) {
        int carry = 0, mul=0;
        for(auto j=v.rbegin();j!=v.rend();j++) {
            mul=i**j + carry;
            carry=mul/10;
            *j=mul%10;
        }
        if(carry)
            v.insert(v.begin(),carry);    
    }
    for(int i:v)
        cout<<i;
}
int main()
{
    int n;
    cin >> n;
    if( n>0 && n<101 )
        bigFactorials(n);
    return 0;
}

问题是crand> 10时,然后插入一个整数值而不将其分成字符,应如下实现

if(carry)
{
    if (carry >= 10)
    {
        while (carry > 0)
        {
            v.insert(v.begin(),carry % 10); // put each char from carry into v
            carry = carry / 10;
        }
    }
    else
        v.insert (v.begin(),carry);
}

这样,您甚至可以将v作为vector<char>和50!我们有3041409320171337804361260816660647684444443776415689605120000000000000000000000000000000000000000000000000000000000来源。

当我打印出添加到向量的carry值时,您肯定会溢出:

1
5
4
3
3
3
4
6
8
13
20
35
64
121
243
510
1124
2585
6204
15511
40329
108888
304888
884176
2652528
8222838
26313083
86833176
-134263930
-134263930-639604140847618609643520000000

我切换到vector和 carrymullong long,并且能够获得34!的正确答案,但是99!仍然溢出。似乎您需要进一步减少要添加到向量的数字。

您需要以十进制数字分配carry,然后在您的 bigint 中插入。。

while (carry)
{
    v.insert(v.begin(), carry % 10);
    carry /= 10;
}

在这里整个功能:

void bigFactorials(int n) {
    vector<int> v;//If I specify the size as v(1000) it works fine but I don't 
    //want to specify the size beforehand.
    v.push_back(1);
    // Complete this function
    for (int i = 2; i <= n; i++)
    {
        int carry = 0, mul = 0;
        for (auto j = v.rbegin(); j != v.rend(); j++)
        {
            mul = i * *j + carry;
            carry = mul / 10;
            *j = mul % 10;
        }
        while (carry)
        {
            v.insert(v.begin(), carry % 10);
            carry /= 10;
        }
    }
    for (int i : v)
        cout << i;
}

live demo