2012-02-26 91 views
1

我在使用向量,迭代器然後使用const時遇到了問題。在使用向量和迭代器時與常量行爲苦苦掙扎

對於一些背景我試圖創建一個vector<string>寫入方法,所以我可以很容易地打印出矢量內的所有字符串。

這裏的代碼位:

void ArrayStorage::write(ostream &sout) const{ 
    for (vector<string>::iterator stringIt = _dataVector.begin(); 
        stringIt < _dataVector.end(); 
        stringIt++){ 
     sout << *stringIt; 
    } 
} 

ostream& operator<<(ostream &sout, const ArrayStorage &rhs){ 
    rhs.write(sout); 
    return sout; 
} 

當我嘗試這樣我結束了第2行得到一個錯誤:

無法從「std::_Vector_const_iterator<_Myvec>」轉換爲「std::_Vector_iterator<_Myvec>」。

所以,我必須從寫入方法的末尾刪除const,然後爲operator<<工作,我必須從RHS參數中刪除const

這是爲什麼?我不想改變任何班級成員,所以我不明白髮生了什麼......我錯過了什麼?

+1

Totonga的回答應該是正確的。此外,你的循環應該看起來像這樣:for(vector :: iterator stringIt = _dataVector.begin(); stringIt **!= ** _dataVector.end(); stringIt ++){...}通常只有隨機存取迭代器支持** <** or **> **。 – alfa 2012-02-26 14:05:58

+0

除了在帖子中黑入HTML,請點擊組合窗格旁邊的'?'按鈕以瞭解如何格式化SO上的帖子。 – 2012-02-26 14:06:13

回答

6

這就像編譯器告訴你的一樣。使用

::const_iterator 

,而不是

::iterator 

所以

for (vector<string>::const_iterator stringIt = _dataVector.begin(); 
       stringIt != _dataVector.end(); 
       ++stringIt){ 
    sout << *stringIt; 
} 

會工作。與end()比較時,請確保使用!=而不是<。

+0

我覺得很愚蠢......在我發佈這篇文章之後,我想我要去哪裏錯了! 謝謝。 – IdiotCoderCodie 2012-02-26 14:04:14

相關問題