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

mohit picture mohit · Jun 7, 2013 · Viewed 13.8k times · Source

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?

Answer

juanchopanza picture juanchopanza · Jun 7, 2013

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.