Suppose I have a function like this
void foo(std::vector<int> data)
Now I would like to call this function, but the vector I have is quite large and I need to pass only a certain part of it. Obviously I would like to avoid unnecessary copies (the function foo is supposed to make one local copy of the vector with that it's called though).
I would like to achieve something like this:
std::vector<int> largeVector(1e6); // some large data vector
int nPointsToUse = 400; // only a small fraction of it is needed
int offset = 2000;
foo(largeVector.begin() + offset, largeVector.begin() + offset + nPointsToUse)
But that obviously doesn't work, since foo expects one argument which is a vector of ints.
I could just make a copy of only the slice of the data vector before calling foo and then pass the copied vector by reference to the function but I would like to leave its signature unchanged.
Is there a nice way to achieve what I want? So that the function basically calls the constructor of the vector with the arguments I am providing to the function?
Copy elision should apply:
foo({largeVector.begin() + offset, largeVector.begin() + offset + nPointsToUse});
Else change foo to take iterator or range (as std::span).
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