我试图了解为什么binary_search()在find()却找不到某些标点符号的情况下
array<char, 25> punctuation_chars{'\'', '\"', ',', '.', ';', ':', '+', '*', '-', '_', '?', '!', '=', '|', '^', '/', '\\', '(', ')', '[', ']', '{', '}', '<', '>'};
bool is_punctuation(char c)
{
auto ret = find(cbegin(punctuation_chars), cend(punctuation_chars), c) != cend(punctuation_chars);
// auto ret = binary_search(cbegin(punctuation_chars), cend(punctuation_chars), c);
if (c == ',')
cout << c << " is" << (ret ? "" : " not") << " punctuation" << endl;
return ret;
}
注释行不起作用(例如,对于c ==','返回false),而find返回cend(punctuation_chars)...
答案 0 :(得分:2)
punctuation_chars
未排序,因此std::binary_search
不起作用。您需要致电std::sort
:
std::sort(std::begin(punctuation_chars), std::end(punctuation_chars));