Could someone help me, by telling me what this actually does?

I always see this codefor (unsigned int i = 0; i <inventory.size(); ++i) As i'm learning i'm confused what this does and how it works this bit particularly. i <inventory.size(); ++i) could someone explain in a little bit of detail? Here is all the code so far if needed. Thanks in advanced :)

(Not finished)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> inventory;
    inventory.push_back("sword");
    inventory.push_back("armor");
    inventory.push_back("shield");
    
    cout << "You have " << inventory.size() << " items\n";
    
    cout << "\nYour items:\n";
    for (unsigned int i = 0; i <inventory.size(); ++i)
    {
        cout << inventory[i] << endl;
    }
}
This is a typical "for" loop. There are three expressions to a "for" loop, the first two are delimited by a semi-colon (;) :

First, You have an expression that initializes the loop -- this is usually one variable -- I like to think of it as the controlling variable;

Second, You have a test, which is made before each iteration of the loop;

Third, You have an expression that usually is an incrementation of the initializing variable.

So in the example you posted, you have:

1
2
3

for( unisgned int i = 0; i < inventory.size(); i++ )


The first expression is "unisigned int i = 0". This is the initialization expression, and "i" is the controlling variable.

For the second expression you have " i < inventory.size();". This is the test expression. It is executed before anything within the loop.

Finally, the third expression is "i++". This gets after anything within the loop.

So this loop is going through all of the items in the inventory vector and printing each member on its own line.

inventory is a vector. A vector can grow and shrink in size. vector.push_back() appends its arguments to the vector. The for loop, header line is like any other for loop in c++, where instead of the number. size() is a member function of vectors, in which returns the integer value of the size. So if the size is 3, it would be:
i <inventory.size();
converts to:
i < 3;

and basic for loop structure is:
for(counting variable; condition; increment)

So i starts at 0, the loops progresses to inventory's size(), which is 3, which completes teh for loops condition exiting the loop. The ++i increments i on each loop. The unsigned keyword is extra to indicate that i will never be negative.
Last edited on
Thanks people it really helped!
Topic archived. No new replies allowed.