Home > Software engineering >  std::binary_search curious issue with char array
std::binary_search curious issue with char array

Time:08-16

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.

CodePudding user response:

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";
    }
}
  •  Tags:  
  • c
  • Related