简体   繁体   中英

std::binary_search curious issue with char array

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.

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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM