c++ - 如何检查数组索引是否存在

标签 c++ c arrays indexing

我有一个指针 * double 数组,基本上,它们按任何顺序编入索引。

例如,

double[0][0] = 80.0
double[3][0] = 56.8
double[4][0] = 56.7

例如,我如何检查 double[1][2] 是否存在,如果不存在则创建一个。

我不打算使用vectors 或任何'fancy',只是普通数组。

最佳答案

嗯。好吧,如果你真的想用普通数组来做(为什么?),除了依赖一个神奇的值,你无能为力。我建议 std::numeric_limits<double>::quiet_NaN() (NaN = 不是数字)。也就是说:

#include <algorithm>
#include <limits>

double data[10][20]; // maximum dimensions mandatory with arrays. There's
                     // no way around that, and you can't grow it later.

std::fill(data[0], data[0] + 10 * 20, std::numeric_limits<double>::quiet_NaN());

然后您可以稍后检查数组中是否有真实值,如下所示:

if(!std::isnan(data[1][2])) {          // #include <cmath> for std::isnan
  // oh, look, there's a value here!
} else {
  // Nothing here yet. Better fill it
  data[1][2] = 123.0;
}

警告:如果您的计算本身可能会产生 NaN 值,那么您就完蛋了。例如,如果您尝试计算 0.0 / 0.0,就会发生这种情况。或 std::sqrt(-1)std::log(-1)或其他在实数中没有定义值的东西。如果您的计算产生 NaN 并将其写入数组,则此方法的作用就好像该值从未写入那里一样。

关于c++ - 如何检查数组索引是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319183/

相关文章:

c++ - 链接列表打印不正确?

c++ - 客户端无法使用 udp 连接向服务器发送请求

c++ - linux-aio 可以进行类似 sendfile() 的操作吗?

c - C 中动态数组的删除操作

c - K&R 练习 1-20 - 需要一些说明

c++ - 查找间隔之间的素数总和(C++ 程序不适用于大数)

带有 stdin、stdout、stderr 和错误消息的 C 加密程序

python - 将值插入 numpy 数组

php - 以查询形式回显数组值

c++ - 在 Windows XP 中使用 C/C++ 中的动态数组最简单的方法是什么?