c++ - 奇怪的 : vector<int> to int C++

标签 c++ vector

我正在尝试将 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/

相关文章:

C++:合并两个以元组为元素的 vector

c++ - 从 Windows 编辑控件的格式中删除逗号的方法? (C++)

c++ - ifstream 总是返回 "ELF"给对象

c++ - Visual Studio natvis 语句的局部变量

c++ - 传递参数c++时自定义运算符错误

c++ - 将文件传递给几个函数

matlab - 如何找到至少包含矢量 B 的一个元素的单元格 A 的矢量?

c++ - 将数组转换为 vector 的最简单方法是什么?

C++ - 指针问题

matlab - 如何有效地用查找替换函数?