creating references

I am working off a piece of code that i am having problems understanding

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
36
// 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;
	}
}



I am mainly stuck at this line

void display(const vector<string>& inventory);

How is this not creating a reference called inventory, but here vec is being created as a reference

void display(const vector<string>& vec)

I dont follow how they are doing different things
When dealing with function prototypes the names of the parameters are not used by the compiler. They are there to help document the function.

The following two prototypes are equivalent.
1
2
void display(const vector<string>& inventory);
void display(const vector<string>& );


Also if you're compiling for C++11 or higher your function can be simplified by using a range based loop.

1
2
3
4
5
6
7
8
void display(const vector<string>& vec)
{
    cout << "Your items:\n";
    for (auto& itr : vec)
    {
        cout << itr << endl;
    }
}


Sorry, just new to c++ so still slightly confused. The book says all references must be initialised when being declared.

So is a reference being declared here that doesnt reference anything. :/
Topic archived. No new replies allowed.