Gagaganlf
Gagaganlf

Reputation: 61

how inialize a vector <vector <int>> with int array [][]?

I want no initialize a vector <vector <int>> with a matrix int [][] any help? thanks

Upvotes: 3

Views: 6654

Answers (4)

Ashish Chaudhary
Ashish Chaudhary

Reputation: 1

//Example of Vector Initialization

#include<bits/stdc++.h>
 using namespace std;
 int main(){
 int n = 15;
 vector<int> v(n,0);

 for(int i = 0; i < n; i++){
    cout<<v[i]<<endl;
 }
}

//Here I have initialize vector with 0 value you can use any value instead of zero.

Upvotes: 0

vsoftco
vsoftco

Reputation: 56577

For completeness, if you cannot use C++11, you can simply pre-allocate memory for the vector<vector<int>>, and copy the matrix into it in a double loop:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    const int M = 2, N = 3;
    int matrix[M][N] = { 1, 2, 3, 4, 5, 6};

    vector<vector<int>> vm(M, std::vector<int>(N,0)); // pre-allocate memory

    for (int i = 0; i < M; ++i)
        for(int j = 0; j < N; ++j)
            vm[i][j] = matrix[i][j];
}

Or, you can push_back rvalue vectors in a loop, like

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    const int M = 2, N = 3;
    int matrix[M][N] = { 1, 2, 3, 4, 5, 6};

    vector<vector<int>> vm;

    for (int i = 0; i < M; ++i)
        vm.push_back(std::vector<int>(matrix[i] , 
            matrix[i] + sizeof(matrix[i]) / sizeof(int)));
}

The first solution is probably faster for large vectors due to pre-allocation (no need for resizing during push_back).

Upvotes: 1

M.M
M.M

Reputation: 141648

Using C++11:

 int matrix[5][6] = { 1,2,3 /* ...  */ };

 vector<vector<int>> vm;

 for (auto&& row : matrix)
      vm.emplace_back( begin(row), end(row) );

Upvotes: 5

Rahul Tripathi
Rahul Tripathi

Reputation: 172618

Try like this:

type array[2][2]=
{
   {1,0},{0,1}
};

vector<int> vec0(array[0], array[0] + sizeof(array[0]) / sizeof(type) );   
vector<int> vec1(array[1], array[1] + sizeof(array[1]) / sizeof(type) );

vector<vector<type> > vectorArr;
vectorArr.push_back(vec0);
vectorArr.push_back(vec1);

Upvotes: 0

Related Questions