我想出了一段代码,它在我的程序中执行了一个基本功能,但也搞砸了很多其他功能。如果在使用 find_if
找不到匹配项时它不返回 null 项,而是只是打印一条消息,程序继续运行,那么问题就解决了。但是,string_to_item
必须返回一个项目,因为它在需要项目的函数中作为参数调用,任何删除 return items("null")
的尝试都会导致运行时间错误。我的问题是,如果 vector 没有匹配 string item_name
的元素,有什么方法可以让这个函数不返回项目,或者我是否需要重写相关函数?代码是:
items string_to_item( string item_name, vector<items>& item_container ) {
struct comparer {
comparer( string const& item_name)
: item_name(item_name) {}
bool operator()(items const& it) const { return it.name == item_name; }
string const& item_name;
}
comp(item_name);
vector<items>::iterator result = find_if(item_container.begin(), item_container.end(), comp);
int i = distance( item_container.begin(), result);
if ( result == item_container.end() ) {
if( item_container.size() == 0 ) {
cout << "no elements in vector ( get_item )";
}
else {
cout << "You don't see that here";
return items("null");
}
}
return item_container[i];
}
谢谢!
最佳答案
惯用的方法是返回迭代器本身,然后与调用站点中的 item_container.end()
进行比较。
您不能使函数有条件地具有或不具有返回值。
关于c++ - 有没有办法让我创建一个不应该返回值的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156512/