我正在尝试将 int vector 转换为 int。这是我进行的方式:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
uint32_t toInt(vector<int> v)
{
uint32_t x=0;
for(int i=0 ; i<v.size() ; i++)
x+=v[i]*pow(10, v.size()-1-i);
return x;
}
int main()
{
vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << toInt(v) << endl; // displays: 123456787 (???)
}
程序应该输出 123456789,但我得到的是 12345678(!)7(!)。
我在 Code::Blocks 13.12 上使用 GCC (tdm-1) 4.7.1
有人对这个问题有解释和解决方法吗? 谢谢。
最佳答案
我无法想象它会导致你提到的问题,但你进行转换的方式非常丑陋,并且涉及 float 学,因此它可能至少导致某些方面的某种程度的不准确例。
您可以通过稍微不同地进行转换来消除该特定问题。例如:
int toInt(vector<int> const &v) { // pass by reference to avoid copying
int ret = 0;
for (int i=0; i<v.size(); i++)
ret = 10 * ret + v[i];
return ret;
}
或者,您可以使用标准库为您处理更多工作:
int toInt(vector<int> const &v) { // pass by reference to avoid copying
return std::accumulate(v.begin(), v.end(),
0,
[](int v, int digit) { return 10 * v + digit; });
}
当然,这仍然限于适合 int
的值——例如,对于典型的 32 位 int
大约为 20 亿。
关于c++ - 奇怪的 : vector<int> to int C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753790/