如何获取代码以从矩阵输出非零元素?

时间:2019-01-01 05:06:45

标签: c++ vector stdvector adjacency-matrix

我有一个要使用的邻接矩阵(不是在图论中,而是在计算物理中),并且我将在Internet上用C ++搜集的一些内容拼接在一起,这是该项目的其余部分我写了一个。我定义了一个任意的邻接矩阵(9x9),并试图将每行的非零元素转换为向量。运行此代码时,得到以下结果1 1 1 1 1 1 6 1 6 1 6

  int x[9][9] = 
{{0,1,0,0,0,0,1,0,0},{1,0,0,1,0,0,0,0,1},{0,0,0,0,1,1,0,0,0}, 
{0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0}, 
{1,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,1,0,0},{0,1,0,0,0,0,0,0,0}};

{
 vector<int> col;
    for (int j = 0; j < 9; j++)

    {
        if (x[0][j] == 1)
        {
            col.push_back(j);
        }
        else{}
        std::copy(col.begin(), col.end(), 
        std::ostream_iterator<int>(std::cout, " "));

我希望得到1 6,即使这些是结果输出中仅有的两个整数,我也感到困惑,为什么它不只是“ 1 6”。我在这里是否缺少任何错误,或者是否有其他方法可以从组成数组中获得非零元素的预期结果?

1 个答案:

答案 0 :(得分:0)

您应该遍历矩阵的数组及其值,所以请看一下:

#include <iostream>
#include <vector>
#include <iterator>

  int x[9][9] = 
    {{0,1,0,0,0,0,1,0,0},{1,0,0,1,0,0,0,0,1},{0,0,0,0,1,1,0,0,0}, 
    {0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0}, 
    {1,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,1,0,0},{0,1,0,0,0,0,0,0,0}};

int main() {
    for (int j = 0; j < 9; j++){ // loop over matrix's arrays
        std::vector<int> col;
        for (int i = 0; i < 9; i++) { // loop over array
            if (x[j][i] == 1) {
                col.push_back(i);
            }
            //else{}
        }
        std::cout << "Array index: " << j << std::endl;
        std::copy(col.begin(), col.end(), 
        std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }
}

输出:

Array index: 0
1 6
Array index: 1
0 3 8
Array index: 2
4 5
Array index: 3
1
Array index: 4
2
Array index: 5
2
Array index: 6
0 7
Array index: 7
6
Array index: 8
1