Iterate over a vector of 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?
 
V

Victor Bazarov

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?

No, you need a visitor functor:

struct myvectorvisitor {
void operator()(const vector<int>& vi) const
{
for_each(vi.begin(), vi.end(), call_a_function);
}
};

...
vector<vector<int> > vvi;
for_each(vvi.begin(), vvi.end(), myvectorvisitor());

V
 
M

Mark P

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?

There's nothing built-in but you could make one yourself. Here's an
untested, incomplete, and very rough sketch of such an iterator. In the
real world you'd probably want to templatize it, make it more robust,
and maybe imbue it with the properties of standard library iterators so
that it could be used with other std. lib. component.

typedef std::vector<std::vector<int> > VecVecInt;

class VecVecIter
{
public:
VecVecIter( VecVecInt& data) : data( data), cur_vec( data.begin())
{
if( cur_vec != data.end())
cur_int = cur_vec->begin();
}

int& operator*()
{
return *cur_int;
}

VecVecIter& operator++()
{
if( cur_int != cur_vec.end())
++cur_int;
else
{
++cur_vec;
cur_int = cur_vec->begin();
}
}

bool atEnd() const
{
return cur_vec == data.end();
}

private:
VecVecInt& data;
VecVecInt::iterator cur_vec;
std::vector<int>::iterator cur_int;
};
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top