S
S
sabn1k2016-02-13 20:05:59
C++ / C#
sabn1k, 2016-02-13 20:05:59

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

3 answer(s)
A
Alexander Taratin, 2016-02-13
@sabn1k

#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;
}

https://ideone.com/t7aYdA

G
GavriKos, 2016-02-13
@GavriKos

Yes, just use:

void myfuncclear(std::vector<int> param)
{
param.clear();
}

But still, it's better to pass a pointer:
void myfuncclear(std::vector<int>* param)
{
param->clear();
}

I'm not sure that the vector has clear - but the essence is the same.
Of course, you may be confused by the [] operator when passing a pointer ... Do a dereference, or use at.

A
Andrey Surname, 2016-02-20
@AAProfi

// т.к. 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 question

Ask a Question

731 491 924 answers to any question