Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::binary_search curious issue with char array

Tags:

c++

So I i'm implementing a rot13 for fun

const char lower[] = "abcdefghijklmnopqrstuvwxyz";

int main() {
    char ch = 'z';

    if (std::binary_search(std::begin(lower), std::end(lower), ch)) {
        std::cout << "Yep\n";
    } 
    else {
        std::cout << "Nope\n";
    }
}

This outputs nope. Any other character outputs yes.

like image 272
Captain Giraffe Avatar asked Oct 13 '25 11:10

Captain Giraffe


1 Answers

Note that a c-string is not ordered increasingly unless empty (as it ends with '\0'). If you fix it to pass the preceding iterator (that points past 'z', not '\0'), it works:

#include <iostream>
#include <algorithm>

const char lower[] = "abcdefghijklmnopqrstuvwxyz";

int main() {
    char ch = 'z';
    if (std::binary_search(std::begin(lower), std::end(lower) - 1, ch)){
        std::cout << "Yep\n";
    } else {
        std::cout << "Nope\n";
    }
}
like image 171
lorro Avatar answered Oct 15 '25 01:10

lorro