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?
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.
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 (*) ?.
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
.
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 vector
s. 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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With