Extreme iterating

Hi there,
I am encountering a very annoying issue, and I couldn't find any solution knowing that my problem is rather .. uncommon. I need to iterate througn a vector in a const function, and, as my function is called very often, to get more performances I need my iterator to be declared somewhere else than the function, so it doesn't have to get deleted and recreated over and over again. So here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Shop
{
public:
	//methods

	virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const //The function i'm talking about
	{
		//things
		for(m_cit = m_buttonList.begin(); m_cit != m_buttonList.end(); ++m_cit)//m_buttonlist is a std::vector
		{
			//things
		}
	}

private:
	std::vector<MenuButton*>::const_iterator m_cit; // the iterator, member of the class

};


Seems great, huh? Well no. I actually get an error on the "for" line.
It tells me : "You can't use '=' here" and "You can't use the ++ operator here"
The thing is, if I actually declare my iterator in the loop, the compiler stops giving me warnings, but, as I said, I really want to avoid doing that.

Thanks for reading and as always thanks for your help!
to get more performances I need my iterator to be declared somewhere else than the function, so it doesn't have to get deleted and recreated over and over again.


Forget this idea. Just make the iterator local to the function.

Creating/destruction of an iterator is practically free. You won't see a performance drop.

Best approach:

1
2
3
4
5
6
7
8
9
10
11
// if you can use C++11
for( auto& i : m_buttonList )
{
    i->whatever();
}

// or... if you can't use C++11 (update your compiler!)
for(std::vector<MenuButton*>::const_iterator i = m_buttonList.begin(); i != mButtonList.end(); ++i)
{
    (*i)->whatever();
}



EDIT:

in fact... I wouldn't be at all surprised if putting the iterator local to the function performed better than making it a class member.


The point I'm trying to make here... is don't just assume something is going to be slow. Test it out and only optimize it if it's a performance concern.

In this case you are complicating your code for literally no reason.
Last edited on
Would you mind copy and pasting the entire error? The compiler or liker usually gives you a reason that you can't use a certain operator.
The error is he can't modify the iterator because the iterator is a member and the function is const.

But the real issue is that he shouldn't be doing this anyway. The iterator should be local.
Well thanks for your answer, I did as Dish said and it re-works perfectly.
Thanks once again, I'll mark the post as solved
Topic archived. No new replies allowed.