defining a function that checks for duplicates in the array. It is simply a function that checks if the new item you are trying to add is already in the list or not. If it is in the list, the function will return any non-zero value (e.g. 1) to indicate TRUE or 0 for FALSE. This function can be called before adding the item to the array. A sample function call would be like
if (!(inthelist(newItem, array)))
add(newItem, array)
You may also create functions that accepts valid input only and another function displaying the contents of the array.
#include <iostream>
#include <vector>
bool inthelist(const std::vector<int> & arr, const int & value)
{
for(auto && it : arr)
{
if(it == value)
return 1;
}
return 0;
}
int main()
{
std::vector<int> arr = {1,2,3,4,5};
std::cout<<"Array : ";
for(auto && it : arr)
{
std::cout<<it<<"\t";
}
int value=0;
std::cout<<"\nEnter value : ";
std::cin>>value ;
if(!inthelist(arr,value))
{
arr.push_back(value);
}
else
{
std::cout<<"There is such value in array\n";
}
return 0;
}
Comments
Leave a comment