警告:从 NULL 转换为非指针类型 'int'
warning: converting to non-pointer type 'int' from NULL
我需要用c++写一个字典
有一个函数可以通过键 returns 字典的值,但是如果没有值,那么我想 return 类似 NULL 的东西。值 0 不合适,因为它可能是其他键的值。
我可以用什么代替 0?
TValue getByKey(TKey key)
{
for (unsigned i = 0; i < this->pairs.size(); i++)
{
if (this->pairs[i].key == key)
return this->pairs[i].value;
}
return NULL;
}
如果我使用 NULL,它会给我一个警告(g++ 编译器):
warning: converting to non-pointer type 'int' from NULL
NULL
专门为指针赋值。如果你 return 的对象不是指针(或智能指针),那么 returning NULL
是错误的。
如果你return一个int
,那么你只能return一个int
可以表示的值,即0或1或2 ...
如果您想要 return 表示“无值”的值,那么您可以 return std::optional
模板的实例。示例:
std::optional<TValue> getByKey(TKey key)
{
// ...
return std::nullopt;
}
P.S。您可以用标准函数 std::find
.
替换实现线性搜索的循环
P.P.S 如果你有很多值,那么可能要考虑使用另一种具有更快键查找的数据结构,例如 std::unordered_map
.
P.P.P.S 也不要使用 NULL
作为指针。它已被 nullptr
.
废弃
我需要用c++写一个字典 有一个函数可以通过键 returns 字典的值,但是如果没有值,那么我想 return 类似 NULL 的东西。值 0 不合适,因为它可能是其他键的值。 我可以用什么代替 0?
TValue getByKey(TKey key)
{
for (unsigned i = 0; i < this->pairs.size(); i++)
{
if (this->pairs[i].key == key)
return this->pairs[i].value;
}
return NULL;
}
如果我使用 NULL,它会给我一个警告(g++ 编译器):
warning: converting to non-pointer type 'int' from NULL
NULL
专门为指针赋值。如果你 return 的对象不是指针(或智能指针),那么 returning NULL
是错误的。
如果你return一个int
,那么你只能return一个int
可以表示的值,即0或1或2 ...
如果您想要 return 表示“无值”的值,那么您可以 return std::optional
模板的实例。示例:
std::optional<TValue> getByKey(TKey key)
{
// ...
return std::nullopt;
}
P.S。您可以用标准函数 std::find
.
P.P.S 如果你有很多值,那么可能要考虑使用另一种具有更快键查找的数据结构,例如 std::unordered_map
.
P.P.P.S 也不要使用 NULL
作为指针。它已被 nullptr
.