【问题标题】:Is there any way to store a null value in an array of integers?有没有办法将空值存储在整数数组中?
【发布时间】:2021-06-29 02:23:47
【问题描述】:

我正在尝试创建一个整数数组,但我不希望该数组的所有值都是整数类型。我想在某些地方存储null,在其他地方存储整数。例如。

arr[] = {50, 20, null, 30, null, null, 60}

在 java 中,我知道您可以将数组声明为整数并存储 null (Integer[] arr)。有什么方法可以为 C++ 做同样的事情吗?

【问题讨论】:

  • 你不能在数组中存储不同类型的值。但是你可以存储指针,并用nullptr指针留下空值。或者将 std::any 存储到数组中。
  • 没有。您可以认为某个特定值代表“空数据”,但识别空值需要特定于您的程序的逻辑。我想您可以使用 std::optional<int> 的数组,但这并不完全相同。
  • 和java一样,创建一个Integer类

标签: c++ arrays null integer


【解决方案1】:

你不能在数组中存储不同类型的值类型(实际上C++中没有java的null)。但是您可以存储指针,并使用 nullptr 指针保留空值。或者使用 c++17 将 std::any/std::optional 存储到数组中。

#include <any>
#include <array>
#include <memory>
#include <vector>
#include <optional>

int main(int argc, char* argv[]) {
  std::array<std::unique_ptr<int>, 7> ar1 = {std::make_unique<int>(50),
                                             std::make_unique<int>(20),
                                             nullptr,
                                             std::make_unique<int>(30),
                                             {},
                                             {},
                                             std::make_unique<int>(60)};
  std::array<std::any, 7> ar2 = {50, 20, {}, 30, {}, {}, 60};
  std::array<std::optional<int>, 7> ar3 = {50, 20, {}, 30, {}, {}, 60};  
  return 0;
}

【讨论】:

  • 对于std::unique_ptr&lt;int&gt;的情况,定义用户定义的文字是有意义的,所以我们可以写类似50_up而不是std::make_unique&lt;int&gt;(50)
  • @sklott Greate 了解这一点,我还没有看到 make_unique 的任何文字
  • 用户定义的文字可以返回从普通文字生成的任何类型。我的意思是std::unique_ptr&lt;int&gt; operator "" _up(int v) {return std::make_unique(v);}
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2014-02-27
相关资源
最近更新 更多