Thread: iterator pointers

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    iterator pointers

    hi,i got a class toy,and i got 3 pointer objects of that class. all the 3 pointer objects are in a vector and I want a iterator to loop it.

    Code:
    class toy{
    private:
    	string name;
    public:
    	toy(string newName){
    		name=newName;
    	}
    	void  getName(){
    		cout<<name<<endl;
    	}
    };
    int main(void){
    	toy *a=new toy("a");	toy *b=new toy("b");	toy *c=new toy("c");
    	
            vector<toy*>list;
    	list.push_back(a); 	list.push_back(b);	list.push_back(c);
    	//loop to print out all the name.
            vector<toy*>::iterator ptr;int i=0;
    	while(ptr != list.end() ){
    		ptr->getName();
    		ptr++;
    	}
    }
    i get error in the last part.looping to print out all the name.hope some one can help out.thanx alot.

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    And where exactly do you initialize the iterator to point the first element of the list?

    use for loop and fill all 3 places of the for instruction - it will be easier to read.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    58
    Code:
    class toy{
    private:
    	string name;
    public:
    	toy(string newName){
    		name=newName;
    	}
    	void getName(){
    		cout<<name<<endl;
    	}
    };
    int main(void){
    	toy *a=new toy("a");	
    	toy *b=new toy("b");
    	toy *c=new toy("c");
    
    	vector<toy*>list;
    	list.push_back(a);
    	list.push_back(b);
    	list.push_back(c);
    
    	vector<toy*>::iterator ptr;int i=0;
    	
    	for(ptr=list.begin();ptr!=list.end();ptr++){
    		cout<<ptr->getName()<<endl;  //ERROR Line 
    	}
    }
    I tried a for loop,but i still get a new error need help !

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    630
    Code:
    for(ptr=list.begin();ptr!=list.end();ptr++){
    	cout<<ptr->getName()<<endl;  //ERROR Line 
    }
    Code:
    cout << (*ptr)->getName() << endl;

  5. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    thread closed.problem solved.

    problem solved. thank you all for your help

  6. #6
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Are you ever going to derive from toy? I see no virtual functions there. Why are you storing pointers in the vector instead of the objects themselves? (Not that it's wrong, just want to know)

Popular pages Recent additions subscribe to a feed