什么是正确的样式来表明没有什么可返回的
What is the correct style to indicate that there is nothing to return?
我使用 unordered_maps unordered_map存储对象:
std::unordered_map<int, std::unordered_map<int, WorldObject>> _worldObjects;
我使用此函数检索一个对象:
WorldObject& objectAtLocation(int x,int y){
if(_worldObjects.find(x)!=_worldObjects.end() && _worldObjects[x].find(y)!= _worldObjects[x].end()){
//Contains an object
}else{
//Does not contain an object at that location. What should I return ?
}
}
如果在 x,y 处没有存储对象,那么在此函数中指示它的正确方法是什么?
例如,我可以像这样修改函数:
//return value indicating presence of object, output the variable that data is copied into.
bool objectAtlocation(int x,int y,WorldObject& output);
有什么建议吗?
编辑:只使用指针更好吗?
std::unordered_map<int, std::unordered_map<int, WorldObject*>> _worldObjects;
所以我可以做:
WorldObject* objectAtLocation(int x,int y){
WorldObject* result = nullptr;
if(_worldObjects.find(x)!=_worldObjects.end() && _worldObjects[x].find(y)!= _worldObjects[x].end()){
//Contains an object
result = _worldObjects[x][y];
}else{
//Does not contain an object at that location. Returning nullptr:
}
return result;
}
编辑:在坐标(x,y)处没有对象并不例外。因此,我不需要抛出异常。我只想指出,该地点什么都没有。
您能否提供带有答案的示例代码,因为我是C++新手,并且可能无法从您的评论中完全理解?
"标准C++方式"是返回迭代器。如果未找到与您的搜索条件匹配的内容,则返回(编辑:这在您的情况下不起作用,我误读了您如何使用容器)_worldObjects.end()
。
如果您的容器很复杂并且不适合返回迭代器,则可以返回指向对象的指针,如果未找到对象,则返回nullptr
。
编辑:
从您的问题编辑中改编代码示例:
WorldObject* objectAtLocation(int x,int y){
WorldObject *result = nullptr;
const auto xIter = _worldObjects.find(x)
if(xIter !=_worldObjects.end()){
const auto yIter = xIter->find(y);
if (yIter != xIter->end()){
//Contains an object
result = &(*yIter);
}
}
return result;
}
有几种方法可以做到这一点,在我看来,没有理由做一些过于复杂的事情。所以我认为你自己的建议很好。
否则,您可以返回一个指针,然后在找不到任何内容时检查然后返回 null。
或者,您可以实现一个可为 null 的类(可以是模板或您从中继承的类),该类允许您检查实例是否为 null 对象。
不过,您可以为对象定义一个表示 null 的"默认"状态,并且可以对此进行检查,因此只要您找不到任何内容,就可以返回对 null 对象的引用。空对象可以是静态的,也可以不是静态的。
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我可以使用什么来停止循环而不是"返回 0"?
- 这个返回元素位置的基于循环的函数有什么问题?
- 查找不存在的键时,unordered_map返回什么
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 如果我在 const 函数上使用指针,我可以返回什么?
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 什么 /可以/ 你从一个函数返回. 并期望它在到达时还活着?
- 使用枚举作为条件,if 条件将返回什么,真或假?
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 我应该返回什么而不是标准::shared_ptr<>&?
- 返回类型在 C++ OOP 中是什么意思
- 什么 & 返回左值或右值?
- 实际上什么返回类型有一个新的
- 链表缓冲区;应该插入什么返回
- 指针赋值应该使用什么返回类型?