C++ Iterators

Elmo187

Limp Gawd
Joined
Jun 7, 2003
Messages
291
Ok, heres what I'm having a problem with, I'll post a portion of the code that is causing the problem, then see if i can explain what im trying to do.

Code:
    struct Course
    {
    	string name;
    	string grade;
    };
    
    struct Student
    {
    	string firstName;
    	string lastName;
    	string studentNumber;
    	vector<Course> courses;
    	vector<Course>::iterator itCourses;
    };
    
    vector<Student> theStudents;
    vector<Student>::iterator itStudents;	
    
    double getCourseMean(string courseName)
    {
    	itStudents = theStudents.begin();
    	(*itStudents).itCourses = (*itStudents).courses.begin();
 	cout << (*itStudents).(*itCourses).name;		 //Error is thrown here
    	
    }

Right now, all I want to be able to do is access the data held in the courses vector that is contained within the vector "theStudents". Now, when I compile this program, i get an error saying

itCourses was not declared in this scope

So, I'm obviously doing something wrong, but I have no idea what. The vectors are filled in another method that reads in data from a file. I can post all my code if necessary.
 
I'm pretty sure you can print a string with cout but I haven't used C++ in a while. If I remember right, the code ypur trying is trying to print a charactoer pointer to the begining of the string. You need a special print function for strings or do a loop printing each character of the string. Convert this pseudocode or find the function to print strings.

for each char in string
cout << string[n++]
 
The code you've posted has a few different things wrong with it. Since you don't tell us about the exact error message you're getting, it's hard to guess which one you need help fixing. Can you give us the error message that's bothering (completely and exactly, please) or explain what you need fixed?

Perhaps the problem is that the line you've marked has a syntax error; you've coded

Code:
	cout << (*itStudents).(*itCourses).name;

and that won't work. What you want is

Code:
 	cout << (*(*itStudents).itCourses).name;

or, more clearly,

Code:
 	cout << itStudents->itCourses->name;

Meanwhile, you don't need to print each individual character as Powerman is suggesting, that's for sure. operator<< has an override which can accepta a std::string, and prints the whole thing in one call.
 
Ah, that did indeed fix the problem that I was having. It was simply me confusing myself trying to figure out how to properly use iterators, and as a result screwing up the syntax.
 
and the best part about using -> instead of .

...drumroll

it doesn't look like java!

:p
 
Back
Top