Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a part of a vector as a function argument?

Tags:

I'm using a vector in a C++ program and I need to pass a part of that vector to a function.

If it was C, I would need to do the following (with arrays):

int arr[5] = {1, 2, 3, 4, 5}; func(arr+2);  // Pass the part of the array {3, 4, 5} 

Is there any other way than creating a new vector with the last part?

like image 849
mohit Avatar asked Jun 07 '13 11:06

mohit


People also ask

Can you pass a vector by reference?

In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.

How do you pass an array of vectors to a function in C++?

void gridlist(std::vector<int> *grid, int rows, int cols){ ..... } int rows=4; int cols=5; std::vector<int> grid[rows][cols]; gridlist(grid,rows,cols); The only method which has worked for me to pass arrays to a function was by pointer (*) ?.


2 Answers

A common approach is to pass iterator ranges. This will work with all types of ranges, including those belonging to standard library containers and plain arrays:

template <typename Iterator> void func(Iterator start, Iterator end)  {   for (Iterator it = start; it !=end; ++it)   {      // do something   }  } 

then

std::vector<int> v = ...; func(v.begin()+2, v.end());  int arr[5] = {1, 2, 3, 4, 5}; func(arr+2, arr+5); 

Note: Although the function works for all kinds of ranges, not all iterator types support the increment via operator+ used in v.begin()+2. For alternatives, have a look at std::advance and std::next.

like image 123
juanchopanza Avatar answered Sep 27 '22 20:09

juanchopanza


Generically you could send iterators.

static const int n[] = {1,2,3,4,5}; vector <int> vec; copy (n, n + (sizeof (n) / sizeof (n[0])), back_inserter (vec));  vector <int>::iterator itStart = vec.begin(); ++itStart; // points to `2` vector <int>::iterator itEnd = itStart; advance (itEnd,2); // points to 4  func (itStart, itEnd); 

This will work with more than just vectors. However, since a vector has guaranteed contigious storage, so long as the vector doesn't reallocate you can send the addresses of elements:

func (&vec[1], &vec[3]); 
like image 25
John Dibling Avatar answered Sep 27 '22 19:09

John Dibling