【问题标题】:Making a matrix out of an array using std::vector使用 std::vector 从数组中创建矩阵
【发布时间】:2020-12-01 14:13:03
【问题描述】:

我想制作一个将数组转换为矩阵的程序。我做了一些这样的作品,但我对结果不太满意。我得到的输出实际上是有意义的,但我不知道我应该改变什么才能得到我想要的。

矩阵的大小不必是 4x4,它实际上可以是我想做的任何东西,它可以使我从数组中变成 4x4 [15]。

#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>

typedef unsigned int uint;

void print(const std::vector<int>& array)
{
    for(uint i=0; i< array.size(); i++)
        std::cout << array[i] << " ";
    std::cout << "\n" << std::endl;
}

void random(std::vector<int>& array, int size = 4)
{
    srand(time(0));
    std::vector<std::vector<int>> mat;
    for(uint i=0; i<4; i++)
    {
        for(uint j=0; j<4; j++)
        {
            array.push_back(rand()%10);
        }
        mat.push_back(array);
    }

    print(array);
    for(uint i=0; i<4; i++)
    {
        for(uint j=0; j<4; j++)
        {
            std::cout << mat[i][j] << " ";
        }
        std::cout << std::endl;
    }

}



main()
{
    std::vector<int> A;
    random(A);
}

输出示例,因为它是随机的

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 

1 2 3 4 
1 2 3 4
1 2 3 4 
1 2 3 4

我想要的应该是这样的:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

【问题讨论】:

  • 为每一行添加相同的向量array。您应该为每一行定义一个新向量。

标签: c++ arrays matrix vector


【解决方案1】:

array 添加到matmat.push_back(array) 后,需要清除array,否则array 会一直增长。

  std::vector<std::vector<int>> mat;
  for (uint i = 0; i < 4; i++)
  {
    for (uint j = 0; j < 4; j++)
    {
      array.push_back(rand() % 10);
    }
    mat.push_back(array);
    array.clear();       // <<<< add this
  }

将打印mat 的代码更改为:

  for (uint i = 0; i < mat.size(); i++)
  {
    for (uint j = 0; j < mat[i].size(); j++)
    {
      std::cout << mat[i][j] << " ";
    }
    std::cout << std::endl;
  }

如果你不调用array.clear(),你会看到会发生什么,如上所示。

【讨论】:

  • 这一切都很好,但我想在我的数组清除之前存储它,我希望我的矩阵看起来像一个数组但只是分成几部分,我知道如何使用常规数组来做到这一点,但是我想尝试用向量来做。
  • @DimitrijeDjokic 你试过我的建议了吗?国际海事组织它做你想做的事。
  • 我复制粘贴它并得到这个 //empty line //empty line x x x x x x x x x x x x x x x X 是任意数字,因为它是随机的
  • 还将打印 mat 的代码更改为我在您的原始代码中建议的内容,您会看到(并希望理解)会发生什么
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
相关资源
最近更新 更多