简体   繁体   English

如何获取std :: list <std::string> :: iterator输出错误值?

[英]how to get std::list <std::string>::iterator to output error value?

I'm searching through a list of values, and want to have it return some sort of 'default' error value when it cant find the value to search for. 我正在搜索值列表,并希望在找不到要搜索的值时让它返回某种“默认”错误值。 I don't mean std::cerr . 我不是指std::cerr i mean a value that i can use in my program like a bool. 我的意思是我可以在我的程序中使用的值,如bool。 However, if it does find the string, I need the pointer value of where it is in the string. 但是,如果它确实找到了字符串,我需要它在字符串中的指针值。 How do I do this? 我该怎么做呢?

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
}

The idiomatic way is to return an iterator (not a pointer), and return the end iterator when the element was not found. 惯用的方法是返回迭代器(不是指针),并在找不到元素时返回结束迭代器。

But you don't need to write this, because <algorithm> already contains std::find . 但是你不需要写这个,因为<algorithm>已经包含了std::find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM