Advertisement

still more trouble with stl

Started by November 16, 2000 12:51 PM
2 comments, last by WoX 24 years, 1 month ago
when I have declared a listobject in msvc 6.0 std::list&ltBlock> list1; and an iterator std::list&ltBlock>::iterator iterator1; and an object Block block1(bla bla bla bla); that has a memberfunction drawBlock() then in the main loop of the game a do this: list1.push_back(block1); iterator1 = list1.begin(); if(iterator1 != list1.end()) { iterator1->drawBlock(); iterator++; } but the drawBlock function isn''t called at all and nothing happens please help
The function will get called only once in your example anyway, even if there are more items in your list. You should use a loop for stepping through the list and not an if-statement. Besides, your list only has one item, so i think list.begin() == list.end() and it will never execute the after the ''if'' anyway..

Try it this way:

  #include <iostream>#include <list>class Block{public:	void drawBlock(void) { std::cout << "i got called!" << std::endl; }};int main(int argc, char **argv){	Block block1;		std::list<Block> list1;	std::list<Block>::iterator iterator1;		list1.push_back(block1);		for(iterator1 = list1.begin(); iterator1 != list1.end(); iterator1++)		iterator1->drawBlock();			return 0;}  


.entrox
Advertisement
In order to use any STL container, you have to have a working copy constructor. When you do a push_back, it copies the object into the list structure. If your copy constructor and/or assignment operator isn''t "doing the right thing", you can get unpredicable results.

One way around this is to dynamically allocate all of your block objects, and change the list&ltBlock> into a list&ltBlock*&gt. I find this easier a lot of the time, although your iterator will behave like a Block** instead of a Block*.

Here''s two examples of how to iterate through a list and call the draw function:
  // ex1: using Blockusing std::list;list<Block> list1;// ... fill in list1 ..for (list<Block>::iterator it = list1.begin ();     it != list1.end ();     it++){  it->drawBlock ();}// ex2: using Block*using std::list;list<Block*> list2;//... fill in list2 ...for (list<Block*>::iterator it = list2.begin ()     it != list2.end ();     it++){  (*it)->drawBlock ();}  
You should use pre-increment instead of post-increment in that for loop (i.e. ++it and not it++), your creating a useless temporary iterator and it wont always be optimised away.

This topic is closed to new replies.

Advertisement