By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,605 Members | 1,391 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,605 IT Pros & Developers. It's quick & easy.

Iterate over a vector of vectors, etc

P: n/a
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?

Nov 9 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
foxx wrote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 9 '06 #2

P: n/a
foxx wrote:
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;
};
Nov 9 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.