Given a container of pointers to int
s, how can I increment the int
s without using a dereference operator *
within the loop body {}
?
Here's the implementation with the dereference operator in the loop body:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int x = 0, y = 1, z = 2;
auto increment_elements = [](vector<int*>& v) {
for (auto& i : v) { ++*i };
};
increment_elements(vector<int*>{&x, &y, &z});
cout << x << ", " << y << ", " << z << endl;
}
Replacing
for (auto& i : v) { ++*i };
with
for (int& i : v) { ++i };
gives MSVC-2013
error C2440: 'initializing' : cannot convert from 'int *' to 'int &'
.
Why does replacement with
for (auto& i : v) { ++i };
compile but without incrementing the int
s, and what is it doing?
I have the same question regarding replacement with
for (int*& i : v) ++i;
which gives the same result.
Uses references over pointers whenever you can. You can't make vector of reference type so instead you can use a
std::reference_wrapper<int>
.increment_elements
should probably also take a range to stay in line with generic programming. Then useget()
on the elements and increment them:Then you can call it using
begin()
andend()
:Or if you still want to take a vector as an argument, you can just iterate through and increment:
and call it as:
auto
deduces the element type asint*
sodecltype(i)
becomesint*&
which does the same thing as your last example.