2012-10-29 51 views
0

所以我有一個函數,其中KaylesPosition是一個vector<int>稱爲piles類:C++將矢量項目轉換爲單個字符串錯誤?

// Produces a key to compare itself to equivalent positions  
std::string KaylesPosition::makeKey(){ 
    std::vector<int> temp(piles.size()); 
    for (int i = 0;i<piles.size();i++){ 
    temp[i]=piles[i]; 
    } 

    std::sort (temp.begin(),temp.end()); 
    std::string key = "" + temp.at(0); 
    for (int i=1 ; i<temp.size() ; i++){ 
    key.push_back('.'); 
    key.push_back(temp.at(i)); 
    } 

    return key; 
} 

我的期望輸出應該是所有在piles元素有序,用句點分隔的。然而,相反,我得到key返回爲「_M_range_check」。我已經嘗試過使用std :: string.append(),我得到一個空字符串或句點。如何獲得該函數以按預期方式返回piles中的所有值的字符串?

+0

詛咒C++和它的隱性內部 - >炭轉化。像'key + = std :: to_string(temp.at(i))'''可能更適合你。此外,'「」+ temp.at(0)'計算爲一個隨機地址,而不是一個字符串。 – chris

回答

1

這個問題似乎是在這裏:

key.push_back(temp.at(i)); 

您試圖追加到一個字符串一個整數,而不首先得到整數的字符串表示。試着用替換該行:

key += std::to_string(temp.at(i)); // This will only work if your compiler supports C++11 

如果你的編譯器不支持C++ 11,試試這個(不要忘記#include <sstream>):

std::ostringstream o; 
o << temp.at(i); 
key += o.str(); 

或者,如果你有選擇使用升壓(http://boost.org/),嘗試它的lexical_cast:

key += boost::lexical_cast<std::string>(temp.at(i)); 

原因此代碼首先編譯,是因爲push_back接受char作爲參數並且你傳遞了一個int,它被轉換爲char(儘管在這種情況下我希望編譯器會有一個警告)。

P.S .:同樣適用於線

std::string key = "" + temp.at(0); 
+0

我不認爲編譯器針對隱式int-> char轉換髮出警告。 – chris

+0

其實它似乎取決於警告等級 – 2012-10-29 03:16:54

+0

我從GCC 4.7.2或VS11(我自己的警告起起落落)都沒有得到任何東西:http://liveworkspace.org/code/f12876f52980fd7b67a52fe164ec8408 – chris