c++ - 如何将 vector 传递给函数?

标签 c++ function vector

我正在尝试将 vector 作为参数发送给函数,但我不知道如何使其工作。尝试了很多不同的方法,但它们都给出了不同的错误信息。 我只包含部分代码,因为只有这部分不起作用。 ( vector “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);
}

最佳答案

这取决于你是否想通过 vector作为引用或指针(我忽略了按值传递它的选项显然是不可取的)。

作为引用:

int binarySearch(int first, int last, int search4, vector<int>& random);

vector<int> random(100);
// ...
found = binarySearch(first, last, search4, random);

作为指针:

int binarySearch(int first, int last, int search4, vector<int>* random);

vector<int> random(100);
// ...
found = binarySearch(first, last, search4, &random);

内部 binarySearch ,您需要使用 .->访问 random 的成员相应地。

您当前的代码存在问题

  1. binarySearch预计 vector<int>* , 但你传入了 vector<int> (在 & 之前缺少 random )
  2. 您不要取消引用 binarySearch 内的指针在使用它之前(例如,random[mid] 应该是 (*random)[mid]
  3. 你不见了using namespace std;<include> 之后s
  4. 您分配给 first 的值和 last是错误的(应该是 0 和 99 而不是 random[0]random[99]

关于c++ - 如何将 vector 传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5333113/

相关文章:

c++ - 提升 C++ 与 Python 的能力

c++ - 从存储在 std::vector 中的数据创建和保存图片

c++ - 如何访问包含指向字符串的指针的 vector 的元素?

c++ - 如何编写密码安全类?

javascript - 如何在 Javascript 函数之间传递变量?

r - 向量元素之和

javascript - 当 IE 8 中的尺寸更改(高度、宽度)时,VML 中的可拖动元素会卡住

c++ - vector "erase"和 "at"产生错误 (c++)

C++ vector 迭代器 : erase() last item crash

C++ 从指针生成函数