Jump to content
  • Advertisement
Sign in to follow this  
gooner

unknown container types

This topic is 4561 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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();
}
}


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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!