Initializing a vector of vectors having a fixed size with boost assign

前端 未结 4 453
Happy的楠姐
Happy的楠姐 2020-12-04 10:10

Having a vector of vector with a fixed size,

vector > v(10);

I would like to initialize it so that it has in all e

相关标签:
4条回答
  • 2020-12-04 10:31
    #include <vector>
    #include <iostream>
    using namespace std;
    
    
    int main(){
        int n; cin >> n;
        vector<vector<int>> v(n);
        //populate
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                int number; cin >> number;
                v[i].push_back(number);
            }
        }
        // display
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                cout << v[i][j] << " ";
            }
            cout << endl;
        }
    }
    

    Input:

    4
    11 12 13 14
    21 22 23 24
    31 32 33 34
    41 42 43 44
    

    Output:

    11 12 13 14
    21 22 23 24
    31 32 33 34
    41 42 43 44
    
    0 讨论(0)
  • 2020-12-04 10:32

    You don't need to use boost for the required behaviour. The following creates a vector of 10 vector<int>s, with each vector<int> containing 10 ints with a value of 1:

    std::vector<std::vector<int>> v(10, std::vector<int>(10, 1));
    
    0 讨论(0)
  • 2020-12-04 10:36

    I will just try to explain it to those new to C++. A vector of verctors mat has the advantage that you can access its elements directly at almost no cost using the [] operator..

    int n(5), m(8);
    vector<vector<int> > mat(n, vector<int>(m));
    
    mat[0][0] =4; //direct assignment OR
    
    for (int i=0;i<n;++i)
        for(int j=0;j<m;++j){
            mat[i][j] = rand() % 10;
        }
    

    Of course this is not the only way. And if you do not add or remove elements, one can also use the native containers mat[] which are nothing more than pointers. Here's my fav way, using C++:

    int n(5), m(8);
    int *matrix[n];
    for(int i=0;i<n;++i){
        matrix[i] = new int[m]; //allocating m elements of memory 
        for(int j=0;j<m;++j) matrix[i][j]= rand()%10;
    }
    

    This way, you don't have to use #include <vector>. Hopefully, it's clearer!

    0 讨论(0)
  • 2020-12-04 10:38

    This doesn't use boost::assign but does what you need:

    vector<vector<int>> v(10, vector<int>(10,1));
    

    This creates a vector containing 10 vectors of int, each containing 10 ints.

    0 讨论(0)
提交回复
热议问题