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时什么也不做,然后将5添加至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);
}

10-07 12:07
查看更多