C++ 比较来自 2 个不同列表的值以使用 2 个 for 循环消除重复数字。无法正确检测重复项

标签 c++ for-loop duplicates

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 7 中的所有内容,然后在到达第二个 5 时什么都不做,然后将 8 添加到 foundBag。 最后 foundBag 应该包含:3 4 5 7 8

问题是它似乎没有正确检测到该号码已经在 foundBag 中,因此它添加了所有内容。 我一直在使用 visual studio 中的步进功能来查看每个步骤,但我无法弄清楚为什么 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);
}

关于C++ 比较来自 2 个不同列表的值以使用 2 个 for 循环消除重复数字。无法正确检测重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991973/

相关文章:

c++ - 为什么 Valgrind 说一个非常简单的程序杀死了 9 个?

c++ - 内联值的优化

ios - SBJson 与 Facebook sdk iOS 冲突

mysql - 将重复的匹配对分组到一个组中 - SQL

c - 如何使用两个或多个迭代器在 for 循环内递增

python - 查找列表中第一个出现的特定数字的位置[python]

c++ - 将 static const char[] 设置为预定义的 static const char[] 失败

c++ - 读取使用运算符创建的矩阵

javascript - 在 Node js 中 for 循环完成时调用函数

javascript - 使用 False 打破 JavaScript 'For' 循环?