繁体   English   中英

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 个元素存在。我不知道元素存在多少或在哪里。“不存在”是指给定索引处的元素尚未初始化。

让我们假设存在 2 个元素:

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

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

如果索引太大(在这种情况下大于49),返回false;

返回真,如果元素存在于 isPresent(int index);

如果给定索引处的元素不存在,则返回 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() 函数位于我需要编写的数组类下。 给定的测试代码(我无法更改)在 main.js 中。 从 main 开始,将创建我的数组类的一个对象,并将不同的元素从 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)……但这显然是一个糟糕的解决方案,原因与我上面解释的相同,除非您的数组应该只包含正值!

如果使用结构不是问题,我建议您检查这个答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM