【发布时间】:2011-03-16 23:37:52
【问题描述】:
我正在尝试将向量作为参数发送给函数,但我不知道如何使其工作。尝试了很多不同的方法,但它们都给出了不同的错误信息。 我只包含部分代码,因为只有这部分不起作用。 (向量“random”填充了随机但已排序的 0 到 200 之间的值)
更新了代码:
#include <iostream>
#include <ctime>
#include <algorithm>
#include <vector>
using namespace std;
int binarySearch(int first, int last, int search4, vector<int>& random);
int main()
{
vector<int> random(100);
int search4, found;
int first = 0;
int last = 99;
found = binarySearch(first, last, search4, random);
system("pause");
return(0);
}
int binarySearch(int first, int last, int search4, vector<int>& random)
{
do
{
int mid = (first + last) / 2;
if (search4 > random[mid])
first = mid + 1;
else if (search4 < random[mid])
last = mid - 1;
else
return mid;
} while (first <= last);
return -(first + 1);
}
【问题讨论】:
-
不起作用是什么意思?请发布错误。
-
关于更新代码:参数 first 和 last 是来自向量的 值,而不是索引。您也永远不会设置要搜索的值 (search4)!
-
使用
using namespace std;是个坏主意。 Why?