iterating over containers



 DEVELOP > c-Plus-Plus > iterating over containers

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
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

.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER