实施重复检查器的更好方法?

时间:2020-09-11 06:58:03

标签: c++ arrays oop exception

我创建了一个异常处理案例,它应该检测数组集合中是否存在重复项,但是try and catch在for循环内遍历该集合,并且想知道是否存在另一种有效的方法来创建该集合重复检查器。

以下是引发异常的函数:

namespace cs_set {

    template<class ItemType>
    void ArraySet<ItemType>::add(const ItemType& newEntry) {
        //auto result1 = std::find(std::begin(items), std::end(items), newEntry);
        //int locatedIndex = getIndexOf(new);
        if (std::find(std::begin(items), std::end(items), newEntry) != std::end(items))
       {
            throw DuplicateItemError();
       }  
        else 
       {  
            items[itemCount] = newEntry;
            itemCount++;
       }  
    }  

这里是实现它的for循环,想知道我是否可以使其更好或更有效:

void setTester(ArraySet<string>& set)
{
    cout << "isEmpty: returns " << set.isEmpty()
         << "; should be 1 (true)" << endl;
    displaySet(set);

    std::string items[] = {"one", "two", "three", "four", "five", "one"};
    cout << "Add 6 items to the set: " << endl;
    for (int i = 0; i < 6; i++) {
    
        try {
            set.add(items[i]);
            cout << items[i] << endl;
        }
        catch (ArraySet<string>::DuplicateItemError e)
        {
            //set.add(items[i]);
            cout << "IT IS A DUPLICATE!" << endl;
        }
    }

    displaySet(set);

    cout << "isEmpty: returns " << set.isEmpty()
         << "; should be 0 (false)" << endl;
}

0 个答案:

没有答案
相关问题