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?
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.
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) { .. }
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