全负数组上它给出什么
一个常见的写法是 best = 0。拿全是负数的数组跑一遍:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const vector<int> A = {17, 24, 15, 13, 23};
const vector<int> NEG = {-17, -24, -15, -13, -23};
int find_max_bad(const vector<int>& a) {
int best = 0; // ← 这里写的是 0,不是 a[0]
for (int x : a) {
if (x > best) best = x;
}
return best;
}
int main() {
cout << find_max_bad(NEG) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论