Answer to Question #298819 in C++ for Fwvh

Question #298819

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.

1
Expert's answer
2022-02-17T07:39:34-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog