I'm trying to send a vector as an argument to a function and i can't figure out how to make it work. Tried a bunch of different ways but they all give different error messages. I only include part of the code, since it's only this part that doesn't work. (the vector "random" is filled with random, but sorted, values between 0 and 200)
Updated the code:
#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); }
It depends on if you want to pass the vector as a reference or as a pointer (I am disregarding the option of passing it by value as clearly undesirable).
As a reference:
int binarySearch(int first, int last, int search4, vector<int>& random); vector<int> random(100); // ... found = binarySearch(first, last, search4, random); As a pointer:
int binarySearch(int first, int last, int search4, vector<int>* random); vector<int> random(100); // ... found = binarySearch(first, last, search4, &random); Inside binarySearch, you will need to use . or -> to access the members of random correspondingly.
Issues with your current code
binarySearch expects a vector<int>*, but you pass in a vector<int> (missing a & before random)binarySearch before using it (for example, random[mid] should be (*random)[mid] using namespace std; after the <include>sfirst and last are wrong (should be 0 and 99 instead of random[0] and random[99] If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With