I have read that iterators are used to traverse through the elements of container classes. If I wanted to use iterators to move through elements of a 2d vector, how am I going to declare it and use it? Maybe what I said was not too clear, let me rephrase it to be : " how can I iterate through a 2d vector?":confused:


i

you mean a vector like below? There are probably other ways too, but this is how I do it.

vector< vector< string> > theList;
vector<string>::iterator it;

vector<string>& innerList = theList[0];
it = innerList.begin();
for( ; it != innerList.end(); it++)
{
  // blabla
}

Ancient Dragon's example will work for the first elemend of the 2D vector, and you'll probably have to nest it to go through all the rows of the 2D vector.

Do i need to declare another iterator to traverse the rows and another one to traverse each elements? Also, can you show how to do the nesting, since I'm a bit confused?
Thanks.

>Do i need to declare another iterator to traverse the rows and another one to traverse each elements?
Yes. Each row is an independent data structure, so you have no choice but to use two iterators. It's exactly the same as when you build the vector of vectors:

#include <iostream>
#include <iomanip>
#include <vector>

int main()
{
  std::vector< std::vector<int> > v;

  for ( int i = 0; i < 10; i++ ) {
    v.push_back ( std::vector<int>() );

    for ( int j = 0; j < 10; j++ )
      v[i].push_back ( i + j );
  }

  std::vector< std::vector<int> >::iterator row_it = v.begin();
  std::vector< std::vector<int> >::iterator row_end = v.end();

  for ( ; row_it != row_end; ++row_it ) {
    std::vector<int>::iterator col_it = row_it->begin();
    std::vector<int>::iterator col_end = row_it->end();

    for ( ; col_it != col_end; ++col_it )
      std::cout<< std::setw ( 3 ) << *col_it;
    std::cout<<'\n';
  }
}
commented: Glad to see you're posting on DaniWeb again! - joeprogrammer +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.