Home > C/C++ > Using Iterator

Using Iterator

Consider if we have Different Object type but have same parent class. for example Triangle and Square are in herite Shape. you create object from those class and want to draw them on the screen.


class Shape {
protected:
Color color;
public:
virtual void draw();
}

class Triangle {
private:
Vector3 top;
Vector3 bottom_left;
Vector3 bottom_right;
public:
virtual void draw(
// draw Triangle
);
}

class Rectangle {
private:
Vector3 top_left;
Vector3 top_right;
Vector3 bottom_left;
Vector3 bottom_right;
public:
virtual void draw(
// draw Rectangle
);
}

 

we can store them into list


std::list<Shape*> my_list
std::list<Shape*>::iterator it

Shape *my_triangle = new Triangle();
Shape *my_rectangle = new Rectangle();

my_list.push_back(my_triangle);
my_list.push_back(my_rectangle);

 

Then perform iteration to draw

 

for(it=my_list.begin() ; it!= my_list.end() ; it++)
{
(*it)->draw();
}

 

Advertisements
Categories: C/C++
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: