unknown container types

Started by
4 comments, last by gooner 18 years, 4 months ago
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(); } }
Advertisement
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();  }}


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
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
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.
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
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
Thanks!!!!!

This topic is closed to new replies.

Advertisement