[英]std::binary_search curious issue with char array
So I i'm implementing a rot13 for fun所以我为了好玩而实现了一个 rot13
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').请注意,除非为空(因为它以 '\0' 结尾),否则 c 字符串的排序不会增加。 If you fix it to pass the preceding iterator (that points past 'z', not '\0'), it works:如果你修复它以传递前面的迭代器(指向过去的 'z',而不是 '\0'),它可以工作:
#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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.