2016-03-02 50 views
0

我想将int的向量转换为int。这是我如何进行:奇怪:矢量<int> 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(!)。

我使用GCC(TDM-1)上的代码::块4.7.1 13.12

是否有人有一个解释了这个问题,并解决它的方法吗? 谢谢。

+0

[无法复制](https://ideone.com/Ia3csX) – Xirema

+0

[无法重现](http:// ideone。COM/JHyqD9) –

+0

[不能再现(http://coliru.stacked-crooked.com/a/8c6939905f6a28ec) – NathanOliver

回答

4

我无法想象它会导致你引用的问题,但是你进行转换的方式相当丑陋,涉及浮点数学,所以它可能导致至少某种程度的不准确一些案例。

您可以通过稍微不同的方式进行转换来消除该特定问题。例如:

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亿。

+0

谢谢,第一个对我很好!我会记得,即使我仍然不明白为什么发生错误... –

+0

失败的原因是因为浮点数运算(POW是浮点)的计算机上是不准确 – pm100

0

你的代码工作正常,在我的电脑上

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(){ 
    int myints[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
    vector<int> v (myints, myints + sizeof(myints)/sizeof(int)); 
    cout << toInt(v) << endl; 
} 

其中EXCUTE像:

./test 退出代码:0

这台电脑是旧的,运行C++ 98,但我没有看到你的程序不工作的任何理由。也许检查你的记忆溢出。

1

这样做的确切原因我无法重现,但一个简单的解决方法是不使用pow

#include <iostream> 
#include <vector> 

uint32_t toInt(std::vector<int> v) 
{ 
    uint32_t x=0; 
    for(size_t i=0 ; i<v.size() ; i++) 
    { 
     x*=10; 
     x+=v[i]; 
    } 
    return x; 
} 

int main() 
{ 
    std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
    std::cout << toInt(v) << std::endl; 
} 

pow

pow被设计用以计算浮点数的权力,因此它做了一些复杂而昂贵的事情。如果你只是将整数的整数乘上一个整数,那么乘法几乎总是更快。

powstd::pow略有不同。 std::pow是一个模板化的野兽,最终会调用pow,但只能在使用输入数据类型玩游戏之后才会导致奇怪的结果。举个例子,这位提问者遇到了什么:C++ pow unusual type conversion

这只是using namespace std;可以给你的许多方法之一。您可能会惊讶于编译器选择了哪一个pow。在这里阅读更多:Why is "using namespace std" considered bad practice?