C ++:使用传递给函数的值检查重复数组

时间:2016-09-15 20:56:31

标签: c++ arrays iteration

请不要发布包含答案的代码。我想要参加“我自己的代码”。

我有一项任务要求我创建一个集合类。这涉及创建一个函数,该函数根据传入的值检查数组中的当前值是否有重复。例如,

bool set::contains(const value_type& target) const

会检查目标是否在集合中,并根据它是否存在返回true或false。然后,该函数将在插入函数中声明,该函数将目标值插入到集合中。问题?到达代码搜索数组并检查目标值是否存在。

我的班级有以下变量:

data[CAPACITY] //array to store the items, where CAPACITY
               //is a const storing the maximum number of items in the array
size_type used //how much of the array is used

我尝试了以下for循环,它不起作用:

bool set::contains(const value_type& target) const
{
    for (int i = 0; i < used; i++)
    {
        if (target == data[i])
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

我认为这样可行,因为看起来我通过查看使用了多少数组来遍历数组,然后检查数组的每个索引以获取目标值。当我在main函数中测试此代码时,但打印的数值始终为0或NO。

有什么想法?我无法对数组进行排序,因为我们还没有了解到这一点。

1 个答案:

答案 0 :(得分:2)

问题是你在循环中返回false。因此,如果集合中的第一项不等于您要查找的项目,则会立即返回false。你应该等到完成循环 - 如果你还没找到你正在搜索的项目,那么它就不存在了,所以你应该返回false

bool set::contains(const value_type& target) const
{
    for (int i = 0; i < used; i++)
    {
        if (target == data[i])
        {
            return true;
        }
    }
    return false;
}