Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by Reference an vector inline

Tags:

c++

c++17

vector

i'm trying to pass an vector by reference, which gets modified inside the function (lets say, something like sorting the vector)

void dummy(vector<int> &v) { sort(v.begin(), v.end()); }

The above works only when creating the vector like this and passing the reference, which is expected.

int main() {
  vector<int> v = {1, 2, 3};
  dummy(v);
}

I'm trying to figure out, if there is an inline way of doing this ? Usually, if the vector is not getting modified we can do something like this -

int main() {
  dummy({1,2,3})
}

But, when the vector gets modified, it throws an compilation error saying - cannot bind non-const lvalue reference of type 'std::vector&' to an rvalue of type 'std::vector. So, is there a way to send the vector's reference inline?

like image 840
Dinesh Singh Avatar asked Sep 18 '25 01:09

Dinesh Singh


2 Answers

In that case you should write an overload for an rvalue reference, namely:

void dummy(vector<int>&&);

This will work with the temporary object passed to the function.

like image 199
spiridon_the_sun_rotator Avatar answered Sep 20 '25 14:09

spiridon_the_sun_rotator


If the vector is not getting modified, you can use const to reference:

void dummy(const vector<int> &v) { .. }

dummy(vector<int>{1, 2, 3});

You can also use universal references &&:

void dummy(vector<int> &&v) { .. }
like image 27
masoud Avatar answered Sep 20 '25 14:09

masoud