2016-02-27 78 views
1

我有一個字符串的兩個向量:「二進制‘[’:沒有操作員發現

std::vector<std::string> savestring{"1", "3", "2", "4"}; // some numbers 
std::vector<std::string> save2{"a", "b", "c", "d"};  // some names 

我想重新排序基於前者後者,所以它最終被{"a", "c", "b", "d"}我嘗試這樣做:

for (int i=0; i<savestring.size(); i++) 
{ 
    savestring[i] = save2[savestring[i]]; 
} 

但我得到的錯誤:

"binary '[' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Alloc>' (or there is no acceptable conversion)"

這是什麼意思,什麼是錯我的代碼

+0

您不能用字符串索引字符串。您必須先將字符串轉換爲數字。 –

+1

對於未來,請閱讀[最小,完整和可驗證的示例](http://www.stackoverflow.com/help/mcve)意味着什麼。我們不應該猜測你的變量的類型,我不應該通過你的評論挖掘你的例子。 – Barry

回答

2

問題是savestring[i]std::string而在save2[]的方括號內應該有一個整數。因此,解決方案是先編寫一個自定義函數,將std::string轉換爲整數。

所以,這個更改爲:

// Converts a std::string to an int 
int ToInt(const std::string& obj) 
{ 
    std::stringstream ss; 
    ss << obj; 

    int ret; 
    ss >> ret; 

    return ret; 
} 


for(int i=0;i<savestring.size();i++) 
{ 
    savestring[i]=save2[ToInt(savestring[i])]; 
} 

不要忘記在上面寫#include <sstream>包括sstream頭。

+0

我已經試過這個,它不工作..它說:「錯誤C2784:''未知類型'std ::運算符 - (std :: move_iterator <_RanIt>&,const std :: move_iterator <_RanIt2>&)':無法推斷'std :: move_iterator <_RanIt>&'from'std :: basic_string <_Elem,_Traits,_Alloc>'的模板參數 – hornet07

+0

這很奇怪。什麼樣的數據類型是'savedtring'。如果你向我們展示了整個代碼會更好。 –

+0

std :: vector savingtring; – hornet07

0

您正在保存數字,表示爲字符串。在用作數組索引之前,您需要將它們轉換爲數字。

相關問題