Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forwarding constructor arguments in call-by-value (c++)

Tags:

c++

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?

like image 957
mos90 Avatar asked Aug 17 '26 16:08

mos90


1 Answers

Copy elision should apply:

foo({largeVector.begin() + offset, largeVector.begin() + offset + nPointsToUse});

Else change foo to take iterator or range (as std::span).

like image 157
Jarod42 Avatar answered Aug 20 '26 07:08

Jarod42