M
M
mgkirs2013-11-20 01:25:41
C++ / C#
mgkirs, 2013-11-20 01:25:41

HOW to check the presence of array[3][4] element in D or d C++?

HOW to check the presence of an element in a byte[int][int] array in D or d C++?
And then a Range error pops up

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rio, 2013-11-20
@mgkirs

Depending on what "the presence of an element in an array" means. If the array is static, then the element is always there. And if it is dynamic, then in D you can check that such indexes exist, like this for example:

auto array = new int[10][20];

/* ... */

writeln(array.length);  // напишет 20
writeln(array[0].length); // напишет 10

// проверим, что есть элемент [3][4]
if ((array.length < 4) || (array[0].length < 3))
  writeln("fail"); // а вот это не напишет, значит элемент [3][4] доступен.

You can also explicitly catch an exception when a non-existent element is read:
auto array = new int[10][20];

/* ... */

bool isElementExist(int[10][] a, size_t indexA, size_t indexB)
{
  try { auto i = a[indexA][indexB]; }
  catch { return false; }
  return true;
}

/* ... */

writeln(isElementExist(array, 300, 4)); // false
writeln(isElementExist(array, 3, 4)); // true

A
AxisPod, 2013-11-20
@AxisPod

In D, no idea, in C ++, in principle, in no way. Only if you use containers.
And if C and C++ are different programming languages, then D has nothing to do with them at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question