簡體   English   中英

奇怪:矢量 <int> 詮釋C ++

[英]Strange: vector<int> to int C++

我試圖將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(!)。

我在Code :: Blocks 13.12上使用GCC(tdm-1)4.7.1

有人對此問題有解釋並有解決的方法嗎? 謝謝。

我無法想象它會導致您提到的問題,但是您進行轉換的方式非常丑陋,並且涉及浮點數學運算,因此在某些情況下至少會導致一定程度的不准確性。

您可以通過做一些不同的轉換來消除該特定問題。 例如:

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

我無法復制的確切原因,但是一個簡單的解決方案是不使用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異常類型轉換

這只是using namespace std;的多種方法之一using namespace std; 可以得到你。 您可能會對編譯器選擇哪一個pow感到驚訝。 在此處閱讀更多內容: 為什么“使用命名空間標准”被認為是不好的做法?

您的代碼在我的計算機上可以正常工作

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;
}

像這樣執行:

./test 123456789退出代碼:0

這台計算機是舊的並且運行c ++ 98,但是我看不到任何原因導致您的程序無法運行。 檢查您的內存是否溢出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM