在成本字符串和函数中返回 NULL

returning NULL in cost string& function

本文关键字:返回 NULL 函数 字符串      更新时间:2023-10-16

我需要在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
    }
}