去掉上述步骤中的第三步,并且函数返回该值的序号
时间: 2024-02-20 18:01:26 浏览: 20
好的,如果不使用第三步,函数可以返回最接近目标值的元素的序号,而不是该元素的值。以下是修改后的代码:
```c++
#include <iostream>
#include <algorithm>
#include <cmath>
int findClosest(std::vector<int>& arr, int x) {
int n = arr.size();
if (x <= arr[0]) {
return 0;
}
if (x >= arr[n - 1]) {
return n - 1;
}
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
}
else if (arr[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
if (abs(arr[left] - x) < abs(arr[right] - x)) {
return left;
}
else {
return right;
}
}
int main() {
std::vector<int> arr = { 1, 4, 7, 10, 14, 20 };
int x = 12;
std::sort(arr.begin(), arr.end());
int index = findClosest(arr, x);
std::cout << "The closest value to " << x << " is " << arr[index] << ", found at index " << index << std::endl;
return 0;
}
```
输出结果为:The closest value to 12 is 10, found at index 3。