Home > Back-end >  str::find always return 1 even if the value is not present in the array in cpp
str::find always return 1 even if the value is not present in the array in cpp

Time:12-09

int main()
{
    const char* plating[8] = { "Agsdf","AgNsdfi","CuAsdfg","Nsdfi","NsdfiAg","NiPsdfd","Nonsfe","Psfd" };
    bool press = false;
    press = std::find(begin(plating),end(plating),"88love");
    cout<<press<<endl;
    return 0;
}

** OutPut :- 1 **

** Accepted Output :- 0 **

CodePudding user response:

std::find does not return 1. press is not 1 either. What happens is that std::find returns an iterator, which in your case is just a pointer. A pointer converted to a bool is true unless it is nullptr. When printing that true you get 1 in the output.

The right way to use std::find is to compare the returned iterator to end(plating) to know if the string was found. However, your are comparing pointers and even if you call find with a string that is in the array you do not necessarily get the right result.

Instead you should use std::string:

std::vector<std::string> plating = {" ..." ,"..."};
std::string needle{"88love"};
if ( std::find(plating.begin(),plating.end(),needle) == plating.end()) {
    std::cout << needle << " was not found! \n";
}

CodePudding user response:

If std::find() does not find the element it returns an iteretor to last. Therefore changing press = std::find(begin(plating),end(plating),"88love"); to press = std::find(begin(plating),end(plating),"88love")!=last(plating); should solve your problem. The way you try to do it the iterator is cast to a bool, which will be true if the returned iterator points to last.

  •  Tags:  
  • c
  • Related