Reputation: 69
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
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
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
Upvotes: 2