C++数组长度的二进制搜索问题
C++ Binary Search Issue with Array Length
当您
输入"b"或任何东西(考虑已经排序(时,由于某种原因,下面的代码不会给出输出"GOTCHA",但是如果我使用矢量,它可以正常工作! 似乎如果你调试它字符串大小 x->length((-1; 不给出数组的长度,而是给出 0 作为最大长度 解决方案是什么?
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string x[] = { "a", "b", "c", "d" };
string s;
cin >> s;
int max = x->size()-1;
int min = 0;
int middle = (max + min) / 2;
while (min <= max) //BinarySearch Begins
{
middle = (max + min) / 2;
if (s == x[middle]) //if found display message
{
cout << "GOTCHAn";
break;
}
else if (s > x[middle])//if actual string is after first guess increase
min = middle + 1;
else max = middle - 1; //else decrease
}
system("pause");
return 0;
}
你需要这样的东西
int max = sizeof(x)/sizeof(x[0]) - 1;
希望这有帮助!
在下面的代码中,"x"是一个C风格的数组,你应该使用sizeof(x(来返回它的大小。 x->length(( 或 x->size(( 不正确。
int max = x->size()-1;
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- 我的二进制搜索程序只是关闭了
- 二进制搜索的终止点
- 递归二进制搜索与字符串数组
- 测试树是否为二进制搜索树
- 如何二进制搜索结构向量并在适当的索引处插入
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 字符串的递归二进制搜索-C++
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 二进制搜索树没有匹配的函数调用
- 二进制搜索不适用于特定输出
- 如何在向量上进行二进制搜索以找到具有特定id的元素
- 二进制搜索树不变的标头文件
- 二进制搜索树插入带参数参考
- 二进制搜索不变以查找元素的首次出现
- 了解一种神秘地起作用的递归二进制搜索算法