在成本字符串和函数中返回 NULL
returning NULL in cost string& function
我需要在C++上编写自己的哈希映射。它有一个方法.get("some_string"),如果这个字符串不在我的hash_map中,我将返回NULL。但是我无法检查我的程序,如果这个函数返回NULL或字符串。这是我的代码:
if (m.get("some_string"))
cout << m.get("some_string");
和方法:
const string& Map::get(const string& s) {
string_node* pos = find_pos(s);
if (pos)
return pos->val;
else
return NULL;
}
pos->val只是一个字符串。所以我有一个错误,我无法将const字符串转换为bool。问题是我需要做什么,为了防止cout
中的错误,然后我的函数返回NULL
。我该如何检查?
不能为const string&
返回null值。您必须返回对实际字符串对象的引用,该对象将在函数返回后继续存在。
选项:
-
返回可以为空的
const string *
-
在null情况下引发异常。
-
按值返回一个字符串,在null情况下返回一个空(但有效)字符串。这有两个缺点。它复制结果,您再也无法区分null大小写和真正的空字符串值,而不从函数中输出更多信息。
引用不能为null,因此从函数返回NULL
是没有意义的。同样,您使用const string&
作为条件,因此它试图将其转换为布尔,但没有合适的转换。相反,返回一个空字符串并检查返回值是否等于:
if (pos)
return pos->value;
else
return "";
if( m.get("some_string") == "" ) { ... }
如果一个空字符串是一个有效值,那么你可以使用一个输出参数:
bool Map::try_get( const string& key, string& value )
{
string_node* pos = find_pos(s);
if (pos)
{
value = pos->val;
return true;
}
else
{
value = "";
return false;
}
}
如果返回引用,则不能返回NULL。不过你可以有一个特殊的退货箱。让它返回一个空字符串引用,表示哈希不存在。
Boost.Optional
。你可以这样简单地使用它:
boost::optional<std::string> Map::get(const std::string& s) {
// ...
}
int main()
{
if (boost::optional<std::string> os = map.get("asdf"))
{
// *os
}
}
相关文章:
- 如何在映射中返回null
- 为什么返回 NULL 不会破坏函数?
- fopen 在 gdb 中返回 NULL
- 为什么要从main()返回NULL?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- Box2D World.GetBodyList() 返回 NULL,但 World 显然正在更新对象
- boost::p ython:PyErr_Fetch始终返回 NULL 回溯
- 如何在 Visual C++ 中从返回类型为 map 的函数返回 null?
- 如何在C++中返回Null作为引用
- 从模板化函数返回Null对象
- GDALOpen 在 GEOTiff 文件上返回 null
- PyThreadState_GET() 从 PyImport_GetModuleDict() 中返回 NULL
- (位图)LoadImage() 返回 NULL,GetLastError() 返回 0
- 在构造函数处将类对象强制转换为接口始终返回 NULL
- 如何为迭代器返回"null"值?
- 具有 4 个指针的节点的递归插入函数返回 null
- winAPI FindResource 仅在 DLL 中返回 NULL
- 使用 dlopen/dlsym 打开C++共享库 - dlsym 返回 NULL
- SetWindowsHookEx 在挂接到其他线程时返回 NULL
- 尚未归shared_ptr所有的实例的 shared_from_this() 总是返回 null?