C ++如何编写一个函数来检查元素是否存在于动态分配的数组中

C++ How to write a function to check if element is present in a dynamic allocated array

首先,这是一个赋值,只能使用动态分配的数组(不能使用向量或映射)。我收到的提示是创建另一个数组(是否分配所有元素,我不确定)并与原始数组进行比较。

于是,动态分配了一个原始数组,容量为50。 我无法为 myArray 分配值或提供默认值。

int *myArray = new int[50];

并非所有元素都出现在每个索引中。 myArray 可能有 0、10 或 50 个元素 present.I 不知道元素有多少或在哪里 presents.by "not present" 我的意思是给定索引处的元素尚未初始化。

假设存在 2 个元素:

myArray [0] = 10;
myArray [1] = 20;

目标是编写一个具有 3 个要求的 bool isPresent(int index) 函数:

如果索引太大(在本例中大于 49),return false;

return true,如果元素存在于 isPresent(int index) 中;

return false,如果给定索引处的元素不存在。

bool isPresent(int 0){}//this should return true
bool isPresent(int 1){}//this should return true
bool isPresent(int 3){}//this should return false
bool isPresent(int 49){}//this should return false
bool isPresent(int 50){}//this should return false

请帮我完成 bool isPresent() 函数。 对于我可以创建的第二个数组可能对我有帮助,没有关于如何做的要求。我也许可以做类似下面的事情,但我不确定这有什么帮助:

int *myArray2 = new int[50];
for (int i = 0; i < 50; i++)
{
    myArray2[i] = 100;//so I'm assigning 100 to every element for myArray2
                      //to compare?
}

bool isPresent() 函数在我需要编写的数组class 下。给定的测试代码(我无法更改)在 main 中。从 main 中,将创建我的数组 class 的一个对象,并将不同的元素分配给 main 中的 isPresent()。

你有一个动态分配的整数数组

int* myArray = new int[size]; // where 'size' is the number of the elements in the array

函数 isPresent() 必须检查给定索引处是否存在值。

第一个简单的解决方案是像这样默认初始化所有数组元素:

int* myArray = new int[size]();

这样数组中所有元素的默认值为0。

然后 isPresent() 函数只需检查数组中特定索引处的元素是否为 0

if(myArray[index]==0) 
   return false;
return true;

此实现的问题 是我们将 0 视为标志而不是值。如果用户只想将 0 放在索引 5 处怎么办?那么我们的算法只会声明在索引 5 处没有元素,对吗?

另一个简单但 天真的 解决方案是选择另一个值而不是 0(可能是 -999)...但这显然是一个糟糕的解决方案,原因与我解释的相同以上,除非 你的数组应该只包含正值!

如果使用结构没有问题,我建议你检查一下this answer