2012-01-01 71 views
0

我創建迭代器:奇怪的行爲或std ::地圖::爲const_iterator

typename Report::container_type_for_processed_files::const_iterator beg = rep.processed_files().begin(); 
      typename Report::container_type_for_processed_files::const_iterator end = rep.processed_files().end(); 

我的報告類如下:

class Report 
{ 
public: 
typedef std::map<boost::filesystem3::path, 
       std::pair<unsigned long long/*code*/, 
          unsigned long long/*comment*/> > container_type_for_processed_files; 
container_type_for_processed_files processed_files()const; 
private: 
container_type_for_processed_files processed_files_; 
}; 

在CPP處理的文件看起來像:

typename Report::container_type_for_processed_files Report::processed_files()const 
{ 
    return processed_files_; 
} 

但初始化迭代器如第一行所示:

typename Report::container_type_for_processed_files::const_iterator beg = rep.processed_files().begin(); 
      typename Report::container_type_for_processed_files::const_iterator end = rep.processed_files().end(); 
      while (beg != end) 
      { 
       qDebug() << beg->first.c_str();//here I'm getting runtime error 
       fout << "File name: " << (beg->first).c_str(); 


       ++beg; 
      } 

我收到錯誤:傳遞給C運行時函數的參數無效。
試圖初始化迭代器時,我也越來越輸出窗格中的消息:
(內部錯誤:PC 0x201在讀psymtab,但不是在SYMTAB。)
這是怎麼回事?

+2

什麼是'qDebug'? – 2012-01-01 17:25:33

+2

另外,請考慮創建一個最小的測試用例(請參閱http://sscce.org)。 – 2012-01-01 17:27:47

+2

@OliCharlesworth Qt提供的輸出流,用於調試目的。 – 2012-01-01 17:28:02

回答

3

沒有一個編譯樣,我不知道這是你的問題,但是這看起來腥:

container_type_for_processed_files processed_files() const; 

你應該最有可能返回const&到容器那裏,否則該函數將返回(可能是臨時的)底層容器的副本,並且你的迭代器最終會失效(不是迭代器到同一個對象,並且可能迭代器到了終生的臨時對象)。

嘗試:

container_type_for_processed_files const& processed_files() const; 
+1

謝謝,+1,這是很好的發現 – smallB 2012-01-01 17:52:49

+0

@smallB:你忘了給'+ 1':D。 – Nawaz 2012-01-01 17:56:14

0

一個問題是,rep.processed_files()返回底層容器的副本。因此,begend適用於兩個單獨的對象;嘗試從一個映射的開始迭代到另一個映射的末尾是沒有意義的 - 它將遍歷第一個容器的末尾。您應該返回對包含對象的引用。

typename Report::container_type_for_processed_files & Report::processed_files()const 
{ 
    return processed_files_; // Returns by reference 
} 

而你需要&當你定義乞討,結束

typename Report::container_type_for_processed_files::const_iterator & beg = rep.processed_files().begin(); 
typename Report::container_type_for_processed_files::const_iterator & end = rep.processed_files().end(); 

可能還有其他的問題,被別人當作提高。例如,什麼是qDebug

+0

謝謝,就是這樣。 – smallB 2012-01-01 17:52:10