Leo18
Leo18

Reputation: 69

How do I iterate through a two dimensional vector

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?

Upvotes: 3

Views: 9805

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69922

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;
}

Upvotes: 6

yizzlez
yizzlez

Reputation: 8805

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

Upvotes: 2

Related Questions