gpt4 book ai didi

c++ - 带指针的 binary_search

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:59 24 4
gpt4 key购买 nike

我想用指针实现binary_search

#include <cstdlib>
#include <iostream>
using namespace std;

int binary_p(int x[],int size,int target){
int *p=&x[0];
int *q=&x[size];

while(p<q){
int mid=(p+q)>>2;
if (target==x[*mid]) return 1;
else if(target<x[*mid]) q=mid-1;
else p=mid+1;





}
return -1;


}
int main(int argc, char *argv[])
{
int x[]={2,4,6,7,9,10,12};
int size=sizeof(x)/sizeof(int);
int target=9;
cout<<binary_p(x,size,target)<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}

但这是错误列表

  prog.cpp: In function ‘int binary_p(int*, int, int)’:
prog.cpp:10: error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’
prog.cpp:11: error: invalid type argument of ‘unary *’
prog.cpp:12: error: invalid operands of types ‘int*’ and ‘int’ to binary ‘operator*’
prog.cpp:12: error: invalid conversion from ‘int’ to ‘int*’
prog.cpp:13: error: invalid conversion from ‘int’ to ‘int*’
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:30: warning: ignoring return value of ‘int system(const char*)’, declared with attribute warn_unused_result

谁能给我建议

最佳答案

您不能将两个指针相加(或移动或相除),而是将它们相减给出一个整数类型(你可以加和除),所以你可以写像这样的东西:

int* mid = p + (q - p) / 2;

获取指向中间点的指针。

关于c++ - 带指针的 binary_search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com