Как передать вектор в функцию?
Я пытаюсь отправить вектор в качестве аргумента функции, и я не могу понять, как заставить его работать. Пробовал кучу разных способов, но все они дают разные сообщения об ошибках. Я включаю только часть кода, так как это только эта часть не работает. (вектор «случайный» заполняется случайными, но отсортированными значениями от 0 до 200)
7 ответов
Это зависит от того, хотите ли вы передать vector в качестве ссылки или в качестве указателя (я не обращал внимания на возможность передачи его по значению как явно нежелательного).
В качестве справки:
В качестве указателя:
Внутри binarySearch вам нужно будет использовать . или -> для доступа к членам random соответственно.
Проблемы с вашим текущим кодом
- binarySearch ожидает vector<int>* , но вы передаете vector<int> (отсутствует & до random )
- Вы не разыскиваете указатель внутри binarySearch перед его использованием (например, random[mid] должен быть (*random)[mid]
- Вам не хватает using namespace std; после <include> s
- Значения, присваиваемые first и last , неверны (должны быть 0 и 99 вместо random[0] и random[99]
Вам нужно будет передать указатель на вектор, а не на сам вектор. Обратите внимание на дополнительный ‘&’ здесь:
В любое время, когда возникает соблазн передать коллекцию (или указатель или ссылку на нее) функции, спросите себя, не могли ли вы передать пару итераторов. Скорее всего, вы сделаете так, чтобы ваша функция была более универсальной (например, сделать тривиально работать с данными в контейнере другого типа, когда это необходимо).
В этом случае, конечно, не так много смысла, поскольку стандартная библиотека уже имеет совершенно хороший двоичный поиск, но когда/если вы пишете то, что еще не существует, возможность использовать его на разных типах контейнеров часто бывает довольно удобно.
Вы передаете указатель *random , но используете его как ссылку &random
Указатель (что у вас есть) говорит: «Это адрес в памяти, который содержит адрес случайного»
В ссылке говорится: «Это адрес случайного»
Обратите внимание на & .
Вы используете аргумент как ссылку, но на самом деле это указатель. Измените vector<int>* на vector<int>& . И вы действительно должны установить search4 на что-то, прежде чем использовать его.
How to pass a vector to a function?
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:
![]()
7 Answers 7
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).
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 )
- You do not dereference the pointer inside binarySearch before using it (for example, random[mid] should be (*random)[mid]
- You are missing using namespace std; after the <include> s
- The values you assign to first and last are wrong (should be 0 and 99 instead of random[0] and random[99]
![]()
You’ll have to pass the pointer to the vector, not the vector itself. Note the additional ‘&’ here:
You’re passing in a pointer *random but you’re using it like a reference &random
The pointer (what you have) says «This is the address in memory that contains the address of random»
The reference says «This is the address of random»
![]()
Anytime you’re tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn’t pass a couple of iterators instead. Chances are that by doing so, you’ll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).
In this case, of course, there’s not much point since the standard library already has perfectly good binary searching, but when/if you write something that’s not already there, being able to use it on different types of containers is often quite handy.
You’re using the argument as a reference but actually it’s a pointer. Change vector<int>* to vector<int>& . And you should really set search4 to something before using it.
If you use random instead of * random your code not give any error
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.9.4.43608
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Передача вектора в функцию
Передача вектора в функцию
вот например функция void f(vector <int> v) < cout << v.size(); >в нее нужно передать.
Передача вектора в функцию.
Сабж. #include <iostream> #include <vector.h> void show (); // ? int main () < .
Передача вектора в функцию
И снова я сюда) Еще раз всем привет. Как передать ветор в функцию? Пробовал по указателю и ссылке.
Сообщение от Super GT
Сообщение от Super GT
Пишет ошибку: "использование имени типа не допускается."
Добавлено через 44 минуты
Решено, надо было писать
Сообщение от Super GT
Передача вектора в функцию
Не могу понять как передать вектор в параметры метода класса. Сама матрица читается с текстового.
Передача вектора в функцию
Как правильно передавать вектор в функцию? Опускаю подробности его инициализации, проблема в.
Передача в функцию вектора пар
Есть vector<pair<int, float>> myVec;. Есть функция, которая принимает вектор с типом float: void.
Pass Vector by Reference in C++

This article will demonstrate multiple methods about how to pass a vector by reference in C++.
Use the vector<T> &arr Notation to Pass a Vector by Reference in C++
std::vector is a common way to store arrays in C++, as they provide a dynamic object with multiple built-in functions for manipulating the stored elements. Note that vector can have quite a large memory footprint, so one should carefully consider when passing them to functions. Usually, it’s the best practice to pass by reference and evade the whole object’s copy in for the function scope.
In the following example, we demonstrate a function that takes a single vector of int by reference and modifies its elements. vector elements are printed before and after the multiplyByTwo call in the main function. Note that, even though we store the return value in a new variable arr_mult_by2 , we could access it with the original arr name since the elements were modified in the same object and no new copy was returned.
Use the const vector<T> &arr Notation to Pass a Vector by Reference in C++
On the other hand, one can guarantee that the passed reference would be accessible for modification in the function definition. This feature is provided with the const qualifier keyword that tells the compiler to prohibit any modifications to the given object in the current function scope. Note that this may seem optional detail that does not need to be stressed on a developer, but sometimes these keywords may help the compiler to optimize machine code for better performance.