3

To iterate through and print the elements of a single dimensional vector I use,

vector<int> a;
for(vector<int>::iterator it=a.begin();it<a.end();it++)
    cout<<*it;

How do I do the same for a two dimensional Vector?

Leo18
  • 69
  • 1
  • 6
  • 3
    That's depends what you mean by two-dimensional vector. `vector>`? – dlf Apr 25 '14 at 21:23
  • 2
    possible duplicate of [Iterating over 2-dimensional STL vector c++](http://stackoverflow.com/questions/3131991/iterating-over-2-dimensional-stl-vector-c) – pennstatephil Apr 25 '14 at 21:26

2 Answers2

6

Or since we're using c++11...

#include <iostream>
#include <vector>

using namespace std;

int main() {

  vector<vector<int> > v = {{1,2}, {3,4}};
  for (const auto& inner : v) {
      for (const auto& item : inner) {
          cout << item << " ";
      }
  }
  cout << endl;

  return 0;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • 1
    I think it is worth mentioning that your example is also the easiest way to iterate through 2D vectors with different number of elements per column. – gnikit Sep 26 '18 at 00:47
2

If by two dimensional vector you mean vector<vector<int> >, this should work:

vector<vector<int> > v = {{1,2}, {3,4}};
for(auto beg = v.begin(); beg != v.end(); ++beg)
{
    for(auto ceg = beg->begin(); ceg != beg->end(); ++ceg) {
        cout << *ceg << " ";
    }
    cout << endl;
}

Outputs:

1 2
3 4

Live demo

yizzlez
  • 8,757
  • 4
  • 29
  • 44