unknown container types
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();
}
}
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 generic way to iterate over any STL container is...
What SiCrane said.
Edit: Beaten like a rug [rolleyes]
John B
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 SiCraneQuote: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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement