|
-
June 14th, 2012, 01:04 PM
#1
Why do I have to dereference my vector iterator? What does it mean?
I wrote this code to test:
Code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Person {
string name;
int age;
};
int main()
{
// Populate some people and put them into a vector.
Person p1, p2, p3;
vector<Person> ListOfPeople;
p1.name = "Richard";
p2.name = "Mike";
p3.name = "Cheryl";
p1.age = 12;
p2.age = 13;
p3.age = 14;
ListOfPeople.push_back(p1);
ListOfPeople.push_back(p2);
ListOfPeople.push_back(p3);
vector<Person>::const_iterator citer = ListOfPeople.begin();
while ( citer != ListOfPeople.end() )
{
cout << (*citer).name << " is " << citer->age << " years old." << endl;
++citer;
}
return 0;
}
A clean version can be found at http://codepad.org/hAumqzNB with the associated output.
I know this has to do with pointers. I taught myself C++ once before using online tutorials but this book hasnt gone into pointers though it has covered references. This is one thing I never really understood about the language.
My questions:
Why do I have to deference this to make it work?
What exactly does dereferencing normally do?
Why on other sites do they say pointers are a type of iterator?
Lastly, object->member just a synonym of (*object).member and nothing more?
Edit: the book says derefencing gives an lvalue. Which i understand is a nontemporary object. So when you use an iterator does it act as a reference to the vector? Because I know you need lvalues to access data because of scoping issues. So does this essentially make a copy of the object in memory for the purpose of printing to the screen? aka an lvalue?
Sorry if I don't understand properly, its why im here :/
Thanks in advance for all your help!
Senjai
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|