【问题标题】:How to dynamically create a 2d vector如何动态创建二维向量
【发布时间】:2021-04-07 04:21:47
【问题描述】:

vector< vector<int>> arr(n); arr 是一个二维向量。我想从用户那里获取输入“列”,然后是元素。

    for(int i=0;i<n;i++)
    {
        int cols; cin>>cols;
        
        //Statements
    }

我应该如何在 for 循环中创建 cols 大小的向量?

【问题讨论】:

  • 你的意思是要用cols设置向量内每个向量的大小吗?如果是这样,您可能只需为每个人做arr[i] = vector&lt;int&gt;(cols);
  • 你需要两个嵌套循环。想一想。这并不难。
  • The std::vector constructor 有许多重载,包括一个将 value 作为大小之后的第二个参数的重载。您可以在那里提供另一个具有列大小的向量对象。
  • 非常感谢 mediocrevegetable1 zdf 和一些程序员老兄。我做到了。
  • @Chapo144 还可以发布您的解决方案(回答您自己的问题)吗?它可能对遇到此问题的其他人有用。

标签: c++ c++11 vector data-structures c++14


【解决方案1】:

我终于做到了。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //rows=5 and columns are dynamically initialized
    vector<vector<int>> v(5);
    int cols;
    for(int i=0;i<5;++i)
    {
        cout<<"Enter column count for row : "<<i+1<<"\n";
        cin>>cols;
        v[i]=vector<int>(cols);
        cout<<"Enter Data";
        for(int j=0;j<cols;++j)
            cin>>v[i][j];
    }
    cout<<"your data was :-\n";
    for(int i=0;i<5;++i)
    {
        for(int j=0;j<v[i].size();++j)
            cout<<v[i][j]<<"  ";
        cout<<"\n";
    }
}

【讨论】:

    【解决方案2】:

    向量 a(M,向量(N)); 只需在之前声明列,然后将值插入行。 或者你可以使用向量数组。 向量 v[5];

    【讨论】:

      【解决方案3】:

      首先只取列大小。然后创建向量,然后获取输入;

      int col,num;
      cin >> col;
      
      vector<vector<int>> arr(n,vector<int>(col));   
      // this creates a vector of size n, whose elements are in turn vectors of size col
      
      for(int i=0;i<n;i++)
      {
          for(int j=0;i<col;j++)
          {
              cin >> num;
              arr[i][j]=num;
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 2015-05-18
        • 1970-01-01
        • 2015-07-15
        • 2013-05-02
        • 2013-02-22
        • 2011-08-14
        • 1970-01-01
        • 2016-08-11
        • 2011-10-07
        相关资源
        最近更新 更多