I'm working on a program where I have to alter an Add function in a class. In my main.cpp file, I have to add integers to an array like such:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include "header.h"
int main () {
int array_SetB[] = {1, 10, 3, 10, 5, 10};
…
b_set.Add(array_SetB[0]);
b_set.Add(array_SetB[1]);
b_set.Add(array_SetB[2]);
b_set.Add(array_SetB[3]);
b_set.Add(array_SetB[4]);
b_set.Add(array_SetB[5]);
cout << "The current size of set B is " << b_set.GetCurrentSize() << endl;
//should output a size of 4 since there would be 2 duplicates of 10 found
Then, the Add function is supposed to take in a value so long as there is space in the array, and checks for a duplicate in the array. If there is a duplicate, it does not add the value to the array and moves on to the next value added. If there is no duplicate, then it adds the value to the array. Here is the Add function in my Set.cpp file:
template<class ItemType>
bool Set<ItemType>::Add(const ItemType& new_entry)
{
bool has_room_to_add = item_count_ < max_items_;
bool duplicate = false; //no duplicates
if (has_room_to_add) //vector has room to add
{
int store = new_entry; //stores the new input
cout << "store:" << store << endl; //just to check
cout << "count:" << item_count_ << endl; //just to check
if (item_count_ == 0) { //base case, first item should always be added
items_[item_count_] = new_entry;
item_count_++;
store = 0;
}
elseif (item_count_ > 0) { //for all items after items_[0]
for (int i = 0; i < item_count_; i++) {
if (items_[i] == store) {
duplicate = true;
cout << "Duplicate found: Item not added" << endl;
break;
}
elseif (duplicate == false) {
items_[item_count_] = new_entry;
item_count_++;
cout << "Item added!" << endl;
break;
}
}//end for loop
}//end else if
return has_room_to_add;
} // end if
else { //if there is no room to add
has_room_to_add = false;
return has_room_to_add;
}
} // end add
I apologize if my code is messy. I've been trying to get it to work for hours now, but am still unsuccessful in doing so. Please let me know if you need to take a look at my implementation files for further information. Many thanks!
Move check on duplicate outside the loop: now you are checking only first element and if it is not duplicate, add item. And you might want to use standard algorithm like std::find. It will noticeable shorten your code and hides messy nested ifs/loops.