C++ 二分查找查询指定首字母出现的第一个位置
如果输入b,就代表查询首字母为b出现的第一个位置,即0
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; string words[] = {"b", "bb", "ce", "dc", "de"}; int _find(int l, int r, char ch) { if (l >= r) { if (words[l][0] == ch) { return l; } else { return -1; } } int mid = (l + r) / 2; if (ch <= words[mid].at(0)) { return _find(l, mid, ch); } else { return _find(mid + 1, r, ch); } } int main() { char ch; sort(words.begin(), words.end()); while (cin >> ch) cout << _find(0, 4, ch) << endl; }