[英]STL list<mystruct> return problem
我正在嘗試在項目中使用STL列表,但存在以下問題。
我希望我的列表存儲一個結構。 例如這個
struct mystruct
{
int x;
int y;
};
然后我正在使用一個迭代器來訪問列表中的每個結構,像這樣。
list<mystruct> L;
list<mystruct>::iterator lit;
for(lit=L.begin();lit!=L.end();lit++)
{
if(lit->x==1) cout << "<NUM," << lit->x << "> ";
if(lit->y==2) cout << "<ID," << lit->y << "> ";
}
這有效,但我想一次獲得一個結構,所以我做了這個功能
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
但是運行它后出現錯誤,我無法理解為什么會發生。
任何想法出了什么問題?
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
除非您已經在末尾,否則您將進行遞增操作,但是無論是否在末尾,每次都會取消引用。 為了解決該問題,請考慮返回一個指針,如果最后則返回0
指針。
mystruct* Myclass::next(void)
{
if(lit!=L.end() && ++lit != L.end())
{
// dereference to get the struct, and then return the address of the struct
return &*lit;
}
return 0;
// or nullptr in C++0x
}
然后在使用Myclass::next
的代碼中再次檢查0
(或nullptr
)。
如果您正在編寫返回對象(而不是指針)的next()
,那么我認為您還需要編寫has_next()
函數,在調用next()
之前,應調用該函數以檢查列表中是否存在項next()
。 像這樣:
bool has_next()
{
list<mystruct>::iterator temp = lit;
return ++temp != L.end();
}
mystruct Myclass::next(void)
{
if( !has_next())
{
throw "end of the list is reached";
}
++lit;
return *lit;
}
//usage
while(myClassInstance.has_next())
{
mystruct s = myClassInstance.next();
//work with s
}
或者,如果您決定從next()
返回指向mystruct
指針,那么就has_next()
。 您可以這樣寫:
mystruct * Myclass::next(void)
{
++lit;
if( lit == L.end() )
return NULL;
return &(*lit);
}
問題在這里:
mystruct Myclass::next(void)
{
if(lit!=L.end())
{
lit++;
}
return *lit;
}
首先如何定義照明?
其次,如果lit等於L.end(),則應返回一些默認值,而不是取消引用它,因為如果這樣做,則將導致不確定的行為。 如果幸運的話,您的程序將崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.