为什么C ++中的vector不会自动调整大小 [英] Why vector in C++ doesn't resize automatically
本文介绍了为什么C ++中的vector不会自动调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长的阶乘程序,它需要找到最多100个阶乘。它可以在多达33个阶乘上运行,但不能从34个阶乘上运行。有人可以帮助您识别问题。
I've a very long factorial program which needs to find factorial up to 100. It works well up to 33 factorial but not from 34. Can someone help in identifying the problem.
#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;
}
推荐答案
问题是进位> 10 ,然后插入一个整数值而不将其拆分为char,则应按以下方式实现
Problem is when carry > 10, then you insert one integer value without splitting it into chars, it should be implemented as follows
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!我们有
30414093201713378043612608166064768844377641568960512000000000000。
with this you can even keep v
as vector<char>
and for 50! we have
30414093201713378043612608166064768844377641568960512000000000000.
这篇关于为什么C ++中的vector不会自动调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文