簡體   English   中英

奇怪的行為或std :: map :: const_iterator

[英]Strange behavior or std::map::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運行時函數。
嘗試初始化迭代器時,我還在輸出窗格上收到消息:
(內部錯誤:在psymtab中讀取了pc 0x201,但在symtab中沒有讀取。)
這是怎么回事?

如果沒有可編譯的樣本,我不確定這是您的問題,但這看起來很麻煩:

container_type_for_processed_files processed_files() const;

您最有可能將const&返回到那里的容器,否則該函數將返回(可能是臨時的)基礎容器的副本,並且您的迭代器最終將變為無效(不是對同一對象的迭代器,並且可能對臨時對象的迭代器無效)生命已經結束)。

嘗試:

container_type_for_processed_files const& processed_files() const;

一個問題是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

暫無
暫無

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

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