initialising 2d vectors

//2-D vector can be used in this way
#include<iostream>
#include<cstdlib>
#include<vector>
#include<ctime>
using namespace std;
class aj
{
vector<int> v1;
vector<vector<int> > v2;
int m,n;
public:
void input();
void show();
};
void aj::input()
{
int i,j;
cout<<"\nEnter value of rows and column\n";
cin>>m>>n;
srand(time(NULL));

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
v1.push_back(rand()%100+1);
}
v2.push_back(v1);
for(j=0;j<n;j++)//if we dont use this loop every row will be identical
v1.pop_back();
}

}
void aj::show()
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<v2[i][j]<<" ";
cout<<endl;
}
}
int main()
{
aj a;
a.input();
a.show();
system("pause");
return 0;
}

//try this
And what is the queston?

by the way the class design is bad and the vector initialization is also bad.
@vlad: whats bad about class design.. question is how to initialise 2-D vector..
if you have used any other approach please mention it
Why does the class cotain vector v1 if it is used only in function input for initialization vector v2?

It is stupid to use each time the following loop

for(j=0;j<n;j++)//if we dont use this loop every row will be identical
v1.pop_back();
}

Did you hear something about such member functio as clear()? Moreover if vector v1 will be a local object in function input you would not need to call even v1.clear().

What will occur if function input will be called consequently several times?

So your design of he class is very and very bad.

Also I advice you to read at least the description of the member function reserve()
Last edited on
Thanks for your suggestion.. I will get back to you after going through them..
Can you provide me another way of initialising 2-D vector
Well, consider the following code as a base for your class design

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cstdlib>
#include <ctime> 
 
int main()
{
    const size_t M = 10, N = 20;
    const int MAX_VALUE = 100;
    
    std::vector<std::vector<int>> v( M );
    
    std::srand( std::time( 0 ) );
    
    for ( std::vector<int> &w : v )
    {
        w.reserve( N );
        std::generate_n( std::back_inserter( w ), N, 
            [] { return ( std::rand() % MAX_VALUE + 1 ); } );
    }
    
    for ( const std::vector<int> &w : v )
    {
        for ( int x : w ) std::cout << std::setw( 3 ) << x << ' ';
        std::cout << std::endl;
    }
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.