I don't understand this program!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Inventory Displayer
// Demonstrates constant references

#include <iostream>
#include <string>
#include <vector>

using namespace std;

//parameter vec is a constant reference to a vector of strings
void display(const vector<string>& inventory);

int main()
{
    vector<string> inventory;
    inventory.push_back("sword");
    inventory.push_back("armor");
    inventory.push_back("shield");  
    
    display(inventory);

    return 0;
}

//parameter vec is a constant reference to a vector of strings
void display(const vector<string>& vec)
{
    cout << "Your items:\n";
    for (vector<string>::const_iterator iter = vec.begin(); 
         iter != vec.end(); ++iter)
	{
         cout << *iter << endl;
	}
}

He creates a function prototype void display(const vector<string>& inventory); but when he comes to defining the function, he changes inventory to vec? And then it seem he declares a vector inside a for loop?
Sorry, I can't really explain why I don't get that well because I'm just confused.
The parameter names doesn't have to be the same when declaring the function as when it's being defined. What's matter is the parameter types. You can even leave out the parameter names in the declaration if you like.
void display(const vector<string>&);

So if you just had void display(const vector<string> inventory); You would have to define the function as that, but if you place the bitwise & operator. You can change the name of the vector (or what ever the variable is) with something else?
& here means that the argument is passed by reference. It's used here to avoid that the vector is copied when being passed to the function which can be costly, especially if the vector is large. It has nothing to do with having different parameter names. You can always use different names.
Last edited on
Topic archived. No new replies allowed.