I am writing a function in C++ that doubles all the numbers in a vector. My code is:
std::vector<int> maps(const std::vector<int> & values) {
for (unsigned i = 0; i < values.size(); i++)
{
values[i] = values[i] * 2;
}
return values;
}
However this gives the error:
error: cannot assign to return value because function 'operator[]' returns a const value
values[i] = values[i] * 2;
I don't understand this error or what is wrong with my code.
You are passing the vector as const and you are trying to modifying it. Remove const qualifier if you want to modify it.
I don't understand this error...
The error says that the assignment values[i] = ... is illegal
or what is wrong with my code.
You pass values as const vector. This lets the code inside maps to read values at index i, but not write back a new value.
You can fix it by copying the array first, and doing modifications to the copy. It can be done implicitly by removing const and & from the signature of maps:
std::vector<int> maps(std::vector<int> values)
Now that values is passed by value, C++ makes a copy for you before entering maps.
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