Sign in to follow this  
gooner

unknown container types

Recommended Posts

I have a function which takes an unknown container type as a parameter and draws all of the elements. It works fine with a vector, but not with a list. Has anyone got any suggestions as to why??? template <typename Container> void draw_all(const Container &container){ for(int x = 0; x < container.size(); ++x){ container[x]->draw(); } }

Share this post


Link to post
Share on other sites
std::list doesn't support operator[]. To get your code to work with more container types, consider using iterators. ex:

template <typename Container>
void draw_all(const Container & container) {
for (typename Container::const_iterator iter = container.begin();
iter != container.end();
++iter) {
(*iter)->draw();
}
}


Share this post


Link to post
Share on other sites
Lists do not provide operator[] (and if they did, it would be a bad idea to use it, because accessing an item by index in a list is a linear time operation; ie, it takes twice as long to get item 8 as it does to get item 4).

The generic way to iterate over any STL container is...

What SiCrane said.

Edit: Beaten like a rug [rolleyes]

John B

Share this post


Link to post
Share on other sites
Quote:
Original post by JohnBSmall
The generic way to iterate over any STL container is this:
*** Source Snippet Removed ***


You need to use const_iterators, not normal iterators because you've got a const reference to the container.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Quote:
Original post by JohnBSmall
The generic way to iterate over any STL container is this:
*** Source Snippet Removed ***


You need to use const_iterators, not normal iterators because you've got a const reference to the container.

Gaah. True. Sorry 'bout that.

John B

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this