how to traverse the vector

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,k;
cin>>n>>m>>k;
vector < vector < int > > A;

    for(int i=1;i<=n;i++)
    {
    	for(int j=1;j<=m;j++)
    	{
    		
    		A[i].push_back(j);
		}
	}

return 0;
}. this is the code and i want to print all the elements of two dimensional vector.

Here’s what you are looking for…

vector< vector<int> >::iterator row;
vector<int>::iterator col;
for (row = a.begin(); row != a.end(); row++) {
for (col = row->begin(); col != row->end(); col++) {
    cout<<*col<<" ";
}
cout<<endl;
}

That is simple !

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
	int n,m;
	cin >> n >> m;
	//declare vector of appropriate size 
	vector<vector<int> > A(n,vector<int>(m)) ;
	// initialise values in the vector
	for(int i=1;i<=n;i++)
	{
		for(int j=0;j<m;j++)
		{
			A[i][j] = j + 1;
		}
	}
	// print the contents 
	for (int i = 0; i < A.size(); i++)
	{
    	for (int j = 0; j < A[i].size(); j++)
    	{
        	cout << A[i][j] << " ";
    	}
    	cout<<endl;
	}
	return 0;
}

Hope this helps !

2 Likes

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,k;
cin>>n>>m>>k;
vector < vector < int > > A;
vector< vector >::iterator row;
vector::iterator col;

    for(int i=1;i<=n;i++)
    {
    	for(int j=1;j<=m;j++)
    	{
    		
    		A[i].push_back(j);
		}
	}

for (row = A.begin(); row != A.end(); row++) {
for (col = row->begin(); col != row->end(); col++) {
cout<<*col<<" ";
}
cout<<endl;
}
return 0;
} its still not giving the ans

Can you get your pasted code in correct formatting? I can’t get it to use it in ide properly.

http://ideone.com/GJ5Weq this is code @shubham99

@rahulsup : http://ideone.com/SCthz5

thanks @sarvagya3943

@sarvagya , thanks for that code.

@rahulsup , actually you were getting a segmentation fault there.