Answer the question
In order to leave comments, you need to log in
How to use a vector in a function?
I can't understand how, if I specified vectors as function parameters, how to work with them later? How to display their values in functions, etc.? In general, please explain how to use them somewhere else (in this case in a function) besides the usual use in main() as an array.
Answer the question
In order to leave comments, you need to log in
#include <iostream>
#include <vector>
using namespace std;
//Пример передачи по ссылке
void vectorTransform(std::vector<int> &v){
v[0] = 100500;
}
//Пример передачи по указателю
void vectorTransform_1(std::vector<int> *v){
v->at(0) = 100501;
}
int main() {
std::vector<int> someVec = {0,1,2,3,4,5};
std::cout << someVec[0] << std::endl;
vectorTransform(someVec);
std::cout << someVec[0] << std::endl;
vectorTransform_1(&someVec);
std::cout << someVec[0] << std::endl;
return 0;
}
Yes, just use:
void myfuncclear(std::vector<int> param)
{
param.clear();
}
void myfuncclear(std::vector<int>* param)
{
param->clear();
}
// т.к. vector это шаблон, напишем шаблонную функцию вычисления максимума для вектора
template <typename T>
bool Max(std::vector<T> &v, T &result){
if(v.empty()) return false;
result = *v.begin();
for(std::vector<T>::iterator idx = v.begin(); idx != v.end(); idx++)
if(result > *idx) result = *idx;
return true;
};
void main(void){
// Сделаем два вектора разного типа - int и double и заполним их...
std::vector<int> VecInt;
std::vector<double> VecDbl;
VecInt.push_back(1);
VecInt.push_back(5);
VecInt.push_back(6);
VecInt.push_back(7);
VecDbl.push_back(15.5);
VecDbl.push_back(55.3);
VecDbl.push_back(65.3);
VecDbl.push_back(75.7);
VecDbl.push_back(45.5);
VecDbl.push_back(85.3);
VecDbl.push_back(65.3);
VecDbl.push_back(75.7);
// Переменные для результатов
int MaxInt;
double MaxDbl;
// Применим шаблонную функцию к вектору...
Max<int>(VecInt,MaxInt);
Max<double>(VecDbl,MaxDbl);
// Вывод результата
std::cout <<"Max of int = " << MaxInt << std::endl;
std::cout <<"Max of double = " << MaxDbl << std::endl;
return 0;
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question