Reputation: 55
I have a question about iterators.The question is:" How can I access ( if it's a nested iterator ) the element in row, that is higher or below.Here's an example what I mean:
for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
for( auto j = i->begin();j != i->end();j++ )
{
if( *j == 'O' )
{
// here we must analyze an element which is a row higher or lower
}
}
}
Next thing is what I wanted to do ( but it's with vector ):
for( int i = graphMatrix.size();i < graphMatrix.size();i++ )
{
for( int j = graphMatrix.size();j < graphMatrix.size();j++ )
{
if( graphMatrix[i][j] == 'O' )
{
graphMatrix[j][i] == 'X';
}
}
}
I know that vector has fast size function, but to generalize the code, in my mind, it's better to use iterators ( as my mentor said ).So how can I do the same stuff with iterators as with vectors?
Upvotes: 2
Views: 1160
Reputation: 6515
to get the position of you vector from the iterator with std::distance
:
for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
for( auto j = i->begin();j != i->end();j++ )
{
int x = std::distance(graphMatrix.begin(),i);
int y = std::distance(i->begin(),j);
graphMatrix[x][y] = 'x';
}
}
Upvotes: 0
Reputation: 385405
Since iterators are non-numeric, they are not well-suited to this problem.
You can write complex, confusing and possibly costly code with std::distance
and std::advance
, performing "pointer arithmetic" on your iterators... or you can stick with your numeric loop counters approach, which is precisely what I'd do. Especially seeing as you're using vector
s, which have constant-time (and, let's face it, immediate) access to arbitrary elements in arbitrary positions.
If you're wondering why, in this case, iterators are suddenly not the "better" mechanism for iteration that you've been taught they are: it's because one must use the correct tool for the job, and no technology is the correct tool for all jobs.
Upvotes: 5