Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing sub-vector as function argument in c++

Tags:

c++

vector

Given a vector v1 of size 10, I want to pass the 1st, 3rd and 7th element of v1 as a single function argument. Instead of creating another vector v2, copying the three elements from v1 by value and passing the reference of v2, is there any more efficient way to pass the argument (i.e. without creating v2 and copying elements by value)?

like image 323
user39086 Avatar asked Jan 20 '15 12:01

user39086


2 Answers

Depending on desired behavior, you can pass a vector<reference_wrapper> or other container of reference_wrapper:

#include <vector>
#include <functional>

void f(std::vector<std::reference_wrapper<double>>) {}
void g() {
  std::vector<double> v(10);
  f({v[0], v[2], v[6]});
}
like image 126
ecatmur Avatar answered Sep 25 '22 01:09

ecatmur


You say you don't want to create a new vector and copy the needed elements to it - what about a new vector with pointers to the 3 elements? Or a tuple with pointers to the elements?

std::vector<Element> items { e0, e1, e2, e3, e4, e5, e6, e7 };
auto tuple = std::make_tuple(&items[0], &items[2], &items[6]);

Or just a custom parameter struct with 3 fields - pointers to the 3 vector elements?

Or a raw array with pointers to the 3 vector elements? (Maybe with an additional array size function parameter)

std::vector<Element> items { e0, e1, e2, e3, e4, e5, e6, e7 };
Element subItems[3] { &items[0], &items[2], &items[6] };

Many possibilities, but I'd go for a new vector with copies, unless that is unnecessarily expensive, in which case pointers to the original would be a second choice. Creating the vector is really unlikely to be a perf problem.

like image 26
Johann Gerell Avatar answered Sep 22 '22 01:09

Johann Gerell