| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Bob Smith" |
| Date: |
19 Oct 2003 04:18:45 AM |
| Object: |
iterating over containers |
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
.
|
|
| User: "Jonas Mellin" |
|
| Title: Re: iterating over containers |
19 Oct 2003 05:35:46 AM |
|
|
Bob Smith wrote:
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.
any help and advice highly appreciated.
Thank you
/B
.
|
|
|
|

|
Related Articles |
|
|