2011-03-07 42 views
2

我正在通過值列表進行搜索,並希望當它無法找到要搜索的值時返回某種「默認」錯誤值。我不是說std::cerr。我的意思是我的價值,我可以在我的程序中使用像布爾。但是,如果它找到了字符串,我需要它在字符串中的位置的指針值。我該怎麼做呢?如何獲得std :: list <std::string> :: iterator來輸出錯誤值?

+1

'std :: cerr'遠遠不像「錯誤值」;它是一個**位置(流),您可以在其中輸出錯誤消息**。 – 2011-03-07 18:08:00

回答

5
typedef std::list<std::string> MyList; 
MyList mylist; 
MyList::iterator iter = mylist.find("somestring"); 
if (iter != mylist.end()) { 
    // the string was found 
} else { 
    // the string was not found 
} 
4

慣用的方式是返回一個迭代器(而不是指針),並在元素未找到時返回結束迭代器。

但是你不需要寫這個,因爲<algorithm>已經包含std::find

相關問題