#include <iostream> #include <vector> using namespace std; int binarySearch(vector<int>&vec, int target) { int left = 0; int right = vec.size() - 1; int mid = (left + right)/2; while(left < right) { if (vec[mid] == target) //注意 { return mid; } else if (vec[mid] > target) { right = mid-1; } else if (vec[mid] < target) { left = mid + 1; } mid = (left + right)/2; // 注意 } return -1; } int main() { int target = 5; vector<int> vec; for(int i = 0; i< 10; i++) vec.push_back(i); cout << binarySearch(vec, target); return 0; }