Iterate over a vector or vectors, etc

F

foxx

I have 2D data structure, modelled as a vector of vectors of ints.
I'd like to visit each one of the ints and call a function on them.
Is there some smart way of doing this without using a double for loop,?
I mean how could I go about creating a new kind of iterator that knows
how to transverse all the ints in some sequence; or better still, does
STL already have such a feature?
 
M

mlimber

foxx said:
I have 2D data structure, modelled as a vector of vectors of ints.
I'd like to visit each one of the ints and call a function on them.
Is there some smart way of doing this without using a double for loop,?
I mean how could I go about creating a new kind of iterator that knows
how to transverse all the ints in some sequence; or better still, does
STL already have such a feature?

You might be interested in this article (the related figures show up in
pages 1-11):

http://www.ddj.com/dept/cpp/184401715?pgno=12

and/or the library it mentions -- VIGRA.

Cheers! --M
 
M

Marcus Kwok

foxx said:
I have 2D data structure, modelled as a vector of vectors of ints.
I'd like to visit each one of the ints and call a function on them.
Is there some smart way of doing this without using a double for loop,?
I mean how could I go about creating a new kind of iterator that knows
how to transverse all the ints in some sequence; or better still, does
STL already have such a feature?

Maybe you could nest calls to std::for_each() (found in <algorithm>),
but that still will probably boil down to a double for loop.
 
V

Victor Bazarov

Marcus said:
Maybe you could nest calls to std::for_each() (found in <algorithm>),
but that still will probably boil down to a double for loop.

What wouldn't? A recursive head-first handling of the vector?

The point of 'for_each' would be to allow the compiler to optimize
it better (and it should be able to).

V
 
M

Marcus Kwok

Victor Bazarov said:
What wouldn't? A recursive head-first handling of the vector?

Well, the OP explicitly asked if there was a way to do it "without using
a double for loop", or if the STL had that feature. I gave a
suggestion, but with the disclaimer that it might still use a double for
loop, but at least it would be abstracted away into the for_each() call
(like your solution).
The point of 'for_each' would be to allow the compiler to optimize
it better (and it should be able to).

Agreed, though obviously it may also be possible that the compiler can
optimize the double for loop in the same way.
 

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

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top