C++ 比较 2 个不同列表中的值以使用 2 for 循环摆脱重复的数字。无法正确检测重复项
C++ Comparing value from 2 different list to get rid of duplicate number using 2 for loop. Doesn't detect duplicate correctly
ArrayBag foundBag;
int z;
z = getCurrentSize(); // tell you have many items exit in the bag
for (int i = 0; i < z; i++ )
{
int cur = items[i]; //cur is use to hold each number in the vector and items is the first list of number.
bool found = false; // start as false so it doesnt trigger the true right away
for (int j = 0; j < foundBag.getCurrentSize(); j++) // this loop check the number currently inside cur agianst everything in the foundbag at the moment
{
if (foundBag.items[i] = cur)
{
found == true; // << it didnt detect that it have found the number. I think the problem is here
}
}
if (found == true)
{
// do nothing if found since number is already in the foundbag
}
else if (found != true)
{
foundBag.add(cur); // if number is not found in the foundBag add it to the found bag.
}
}
所以我想做的是将现有列表中的值与一个新的空列表进行比较,在本例中该列表被称为foundBag。因此,基本上,它假设从第一个袋子中获取值,然后检查该数字是否存在于第一个袋子,如果没有找到,它会将该数字添加到foundBag中。如果已经找到了该数字,它将不采取任何行动,并移到第一个袋子的下一个元素。
假设第一个袋子的数字是3 4 5 7 5 8,它应该把3 4 5的所有东西都加起来,然后当它到达第二个5时什么都不做,然后把8加到foundBag上。最后发现袋子应该包含:3 4 5 7 8
问题是它似乎没有正确检测到这个数字已经在foundBag中,所以它添加了所有内容。我一直在使用visualstudio中的step-over函数来查看每一步,但我不明白为什么当它找到相同的数字时,bool仍然为false。
我的英语不是很强,所以如果这没有意义,请要求更多的解释
谢谢
看起来您的=
和==
混淆了。
if (foundBag.items[j] == cur) // Use == here for comparison
{
found = true; // Use = here for assignment
}
顺便说一句,如果你所做的只是在集合中寻找一个元素,那么你更喜欢标准库中的算法:
auto result = std::count(std::begin(foundBag.items), std::end(foundBag.items), cur);
if (result == std::end(foundBag.items)) {
// Not found; Add it
foundBag.add(cur);
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 使用CMake检测支持的C++标准
- 如何用数字处理log(0)
- 当套接字连接断开时检测C/C++Unix
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 如何检测字符串中的"[" + 数字 + "]"并找到最高数字
- 如何在字符串中检测不同的字母和数字
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 如何检测控制台输入不是C++中的数字
- C++ 比较 2 个不同列表中的值以使用 2 for 循环摆脱重复的数字。无法正确检测重复项
- 检测几乎为零并将其替换为 0.0 或将它们保留为小数字是否更快?
- 从字符串中检测数字而不是字母的方法.(目前使用istringstream)
- 在检测字符串是否包含数字字符时,这有什么问题
- 如何检测QString是否由所有数字字符组成
- 使用UTF8CPP时如何检测空白或数字