Dominix
Dominix

Reputation: 280

Basic binary_search in C++ using STL

I am just playing with some STL Algorithms. While using binary_search I am stuck. I have sorted the vector dictionary & then I am running binary_search by writing my own comparator function. However each time the output printed is "not found". However the strings that I search for are there in vector. Any help would be appreciated.

Here is the snippet:

bool ownComparator(const string &a, const string &b){
   return lexicographical_compare(a.begin(),a.end(),b.begin(),b.end());

}
...
...
cout<<"Now using Binary Search to search in sorted array"<<endl;
string searchStr="will";
bool b = binary_search(dictionary.begin(),dictionary.end(),searchStr, ownComparator);
if(b) cout<<"Found";
else cout<<"Not Found";

Upvotes: 2

Views: 303

Answers (2)

Torsten
Torsten

Reputation: 24184

cout << "Now using Binary Search to search in sorted array"

sorted array are keyword. Your string is not sorted array. If you transaform string to sorted array you get alphabetical order string, such "abbbcccddddd...".

Upvotes: 0

Dominix
Dominix

Reputation: 280

Got the solution: When I searched with string searchStr="will\r"; it says found that means while reading from a file, line by line into a vector a \r is appended to the string. Hmm silly mistake.

Upvotes: 2

Related Questions