找 24 要比几次
运行下面这段程序,它数的是「比了几次」:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int lsteps(const vector<int>& a, int target) {
// 线性查找比了几次:找到就停,找不到就是全部比一遍
int n = 0;
for (int x : a) {
n++;
if (x == target) return n;
}
return n;
}
int main() {
vector<int> A = {13, 15, 17, 23, 24};
cout << lsteps(A, 24) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)