+ 1

More questions from a newbie

I am going through a book Learn c++ through game programming. I am on chapter 6 which is using references. Can someone help me understand what is going on in this code? https://code.sololearn.com/c7W8kffkVuXD/#cpp. Let me try to show what I think I understand. void display(cons vector<string>& inventory); So I believe that this is a function ? I dont understand what is going on inside (). Its even more confusion when you look at the definition of the function 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; } } Im so confused by it I dont even know what questions to ask please help. I "THINK" that void display(const vactor<string>& vec) is creating a reference that references inventory and names it vec so vec is a vector of strings that are = vector<string> inventory. what is also confusing me is why in the top void display it says void display(const vector<string>& inventory) and why is there an & there. I think what is really throwing me is how in the function prototype it says void display(const vector<string>& inventory) but in the definiton of the function it is void display(const vector<string>& vec) I dont understand how the definition can differ from the prototype and still work.

17th Jun 2017, 9:58 PM
Bryan
2 Answers
+ 5
in for loop you simply iterate (go through) the vector and print each element's value. For that you create an iterator: vector<string>::const_iterator iter = vec.begin(); this assignment means that your iterator is currently pointing to beginning of vector. To hop over to another element, you write ++iter; And you do this until iterator reaches vector's end: vec.end();
17th Jun 2017, 10:27 PM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 2
The & means that it has to reference it, so that no unnecessary copying is done. Usually with data types like a vector, which can be huge, you don't want to do any unnecessary copying. All it does is get the address of where the vector is. In prototyping the variable's name has no meaning. You can even completely remove it and it would still work. So thats why it still works even though it says "inventory" in the prototype and "vec" in the definition.
17th Jun 2017, 10:15 PM
Dennis
Dennis - avatar