简体   繁体   English

如何使用int array [] []初始化vector <vector <int >>?

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

I want no initialize a vector <vector <int>> with a matrix int [][] any help? 我想不用矩阵int [][]任何帮助初始化vector <vector <int>>吗? thanks 谢谢

Using C++11: 使用C ++ 11:

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

 vector<vector<int>> vm;

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

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: 为了完整起见,如果你不能使用C ++ 11,你可以简单地为vector<vector<int>>预先分配内存,并在双循环中将矩阵复制到其中:

#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 vector s in a loop, like 或者,你可以在一个循环中push_backvector ,就像

#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 ). 由于预分配(在push_back期间不需要调整大小),第一个解决方案对于大向量可能更快。

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);

//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. //这里我用0值初始化向量,你可以使用任何值而不是零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM