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

本文关键字:数字 检测 for 列表 比较 C++ 循环      更新时间:2023-10-16
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);
}