而数组中的每个值都与特定的 int 值不同

while every value in array is different than specific int value

本文关键字:int 数组      更新时间:2023-10-16

我有一个值数组,例如 1、4、7、2。 我还有另一个值数组,我想将其值添加到第一个数组中,但前提是它们都与此数组中已有的所有值不同。如何检查?我尝试过多种类型的循环,但我总是以迭代问题结束。 你能告诉我如何解决这个问题吗?我用 c++ 编写代码。

int array1[7] = {2,3,7,1,0};
int val1 = rand() % 10;
int val2 = rand() % 10;
int array2[2] = {val1, val2};

我正在尝试将数组 2 中的每个值放入数组 1 中。我试过循环

for (int x:array2)
{
while((val1 && val2) == x)
{
val1 = rand() % 10;
val2 = rand() % 10; 
}
}

等等,但仍然无法弄清楚。我有这个问题,因为我可能有不同数量的 array2 元素。因此,它使这个"&&"解决方案无限。 这只是一个示例,可以更清楚地显示它,我的代码有更多的行。

好的,你在这里遇到了一些问题。如果我了解问题,这就是您想要的:

一个。array1 已经填充了多个值,但末尾有空格。 1. 您如何识别数组中已有的条目数与额外的条目数?

二.您有第二个由两个随机值创建的数组。没关系。

您希望将值从 B 追加到 A。 2. 如果 A 的初始长度加上 B 的初始长度大于分配给 A 的总空间,则您有一个新问题。

现在,其他人会告诉您使用标准模板库,但是如果您在此级别遇到问题,您应该知道如何自己执行此操作,而无需混乱库的额外帮助。所以这是一个解决方案。

class MyArray {
public:
int * data;
int count;
int allocated;
MyArray() : data(nullptr), count(0), allocated(0) {}
~MyArray() { if (data != nullptr) free(data); }
// Appends value to the list, making more space if necessary
void add(int value) {
if (count >= allocated) {
// Not enough space, so make some.
allocated += 10;
data = (data == nullptr) malloc(allocated * sizeof(int))
: realloc)data, allocated * sizeof(int));
}
data[count++] = value;
}
// Adds value only if not already present.
void addUnique(int value) {
if (indexOf(value) < 0) {
add(value);
}
}
// Returns the index of the value, if found, else -1
int indexOf(int value) {
for (int index = 0; index < count; ++index) {
if (data[index] == value) {
return index;
}
}
return -1;
}
}

此类为您提供整数的动态数组。它真的很基本,但它教你基础知识。它可以帮助您了解使用旧式 C 样式 malloc/realloc/free 分配/重新分配空间。这是我在80年代写的代码。

现在,您的主代码:

MyArray array;
array.add(2);
array.add(3);
array.add(7);
// etc. Yes, you could write a better initializer, but this is easy to understand
MyArray newValues;
newValues.add(rand() % 10);
newValues.add(rand() % 10);
for (int index = 0; index < newValues.count; ++index) {
array.addUnique(newValues.data[index]);
}

做。

其中的关键部分是addUnique函数,它只是首先检查您要添加的值是否已在数组中。如果没有,它将值追加到数组并跟踪新计数。

最终,当使用这样的整数数组而不是C++中可用的更高级的类时,您必须自己跟踪数组的大小。int[] 上没有神奇的 .length 方法。如果需要,您可以使用一些指示列表末尾的魔术值。或者,您可以执行我所做的操作并保留两个值,一个保存当前长度,另一个保存您分配的空间量。

对于编程,总是有多种方法可以做到这一点。

现在,这是很多代码。使用标准库,您可以将所有这些减少到大约 4 或 5 行代码。但是你还没有准备好,你需要了解引擎盖下发生了什么。不要使用花哨的库,直到你可以手动完成。这是我的信念。