iterating over containers

B

Bob Smith

Hi all,
I have noticed that I over and over again write member functions which
iterate over vectors and other containers.
Is there a standard way of doing this, like assigning a template
function to a range of container iterators?

<example code>

//show the eventui vector
int y = 20, v_interval = 20;
std::vector<QxEventUI*>::iterator it = m_widget_vector.begin();
while( it != m_widget_vector.end() ){
(*it)->show();
y+=v_interval;
it++;
}
</example code>

In the above example I iterate and execute show() for each vector
element. I'd like to set a template function for the iteration and for
each element execute it, how to do that?

any help and advice highly appreciated.
Thank you
/B
 
J

Jonas Mellin

Bob said:
Hi all,
I have noticed that I over and over again write member functions which
iterate over vectors and other containers.
Is there a standard way of doing this, like assigning a template
function to a range of container iterators?

<example code>

//show the eventui vector
int y = 20, v_interval = 20;
std::vector<QxEventUI*>::iterator it = m_widget_vector.begin();
while( it != m_widget_vector.end() ){
(*it)->show();
y+=v_interval;
it++;
}
</example code>

In the above example I iterate and execute show() for each vector
element. I'd like to set a template function for the iteration and for
each element execute it, how to do that?

You can use the 'for_each' generic algorithm:

template<class InputIterator, class Function>
Function for_each(InputerIterator first, InputIterator last, Function func);

a partial solution based on your example:

void showQxEventUI(QxEventUI * element) {
element->show();
}

void (*pfi=)(int)=showQxEventUI;
for_each(m_widget_vector.begin(),m_widget_vector.end(),pfi);

If you need to update the elements, the 'transform' generic algorithm
can be used.

In both cases, a problem remains to udate variables outside the scope of
the function or object in the list. For example, your y and v_interval
variables in your example.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top