Jason McEntire
Jason McEntire

Reputation: 37

is a ++ before a container the same as moving the index by one?

I am unfamiliar with this syntax: ++fCount[index]. Where list is another vector.

I was thinking it was the same as below, but its not:

int i = 0;
vector<int> fCount(1001,0);
for(auto index : list)
{
    fCount[i] = index;
    i++;
}

piece of code:

vector<int> fCount(1001,0);
for(auto index : list)
{
    ++fCount[index];
}

Upvotes: 2

Views: 95

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596352

vector::operator[] returns a reference to an element at a given index.

The ++ increment operator increments the value of a variable.

The two codes examples you have shown are NOT equivalent.

The first code is looping through list, assigning each of its elements as-is to sequential elements of fCount. A range-for loop does not provide access to the indexes of the elements being iterated through, so a separate i variable is being used to index into fCount, where i is initialized to index 0, and i++ increments the value of i by 1 on each loop iteration. For example:

vector<int> list = {5, 10, 15, 20, ...};

int i = 0;
vector<int> fCount(1001,0);
for(auto index : list)
{
    fCount[i] = index;
    i++;
}

This is effectively filling fCount like this:

vector<int> fCount(1001,0);
fCount[0] = 5;
fCount[1] = 10;
fCount[2] = 15;
fCount[3] = 20;
...

The second code is using each element of list as an index into fCount, using the ++ operator to increment the value of each indexed element of fCount. This is because ++fCount[index] is using the prefix increment operator, which has a lower precedence than vector::operator[], so ++fCount[index] is parsed as ++(fCount[index]), not as (++fCount)[index] (IOW, fCount is indexed into first, and then the increment is applied to what operator[] returns). And since fCount is initialized with 0s before the loop, after the loop finishes then every element that was indexed will have a value of exactly 1. For example:

vector<int> list = {5, 10, 15, 20, ...};

vector<int> fCount(1001,0);
for(auto index : list)
{
    ++fCount[index];
}

This is effectively filling fCount like this:

vector<int> fCount(1001,0);
fCount[5] += 1;
fCount[10] += 1;
fCount[15] += 1;
fCount[20] += 1;
...

Upvotes: 2

Related Questions