【问题标题】:How do I work with <vector<vector<bool>> in C++?如何在 C++ 中使用 <vector<vector<bool>>?
【发布时间】:2021-03-04 10:01:34
【问题描述】:

如果我想使用 类型,我想知道如何初始化一个 0 的矩阵,并且是否可以像使用整数矩阵(例如:matrix[row][col] = 1)

编辑:

例如,我正在尝试制作一个 NxN 矩阵:

int n = 5;
std::vector<std::vector<bool>> (n, std::vector<bool>(n, false))

这给了我以下错误

error: no match for call to ‘(std::vector<std::vector<bool> >) (int&, std::vector<bool>)’

作为参考,如果我这样做,我会得到同样的错误:

int n = 5;
std::vector<bool> row(n, false);
std::vector<std::vector<bool>> (n, row)

【问题讨论】:

  • 你考虑过std::bitset吗?
  • 请使用您尝试过的编码示例编辑您的文本;没有图片。

标签: c++ matrix vector initialization boolean


【解决方案1】:

您的错误是试图将内部vector 命名为传递给外部vector 的构造函数:

std::vector<std::vector<bool>> matrix(n, std::vector<bool> row(n, false))
//                            You can't name the temporary ^^^

应该是:

std::vector<std::vector<bool>> matrix(n, std::vector<bool>(n, false))

【讨论】:

    【解决方案2】:

    当然可以。布尔值向量的向量可能不一定是最有效的方法(a),但它肯定是可行的:

    #include <iostream>
    #include <vector>
    
    using tMatrix = std::vector<std::vector<bool>>;
    
    void dumpMatrix(const std::string &desc, const tMatrix matrix) {
        std::cout << desc << ":\n";
        for (const auto &row: matrix) {
            for (const auto &item: row) {
                std::cout << ' ' << item;
            }
            std::cout << '\n';
        }
    }
    
    int main() {
        tMatrix matrix = { {1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 0}};
        //tMatrix matrix(2, std::vector<bool>(3, false));
    
        dumpMatrix("before", matrix);
        matrix[0][2] = 1;
        dumpMatrix("after", matrix);
    }
    

    该程序的输出表明这两个方面都有效,初始化和更改单个项目的能力:

    before:
     1 0 0 <- note this final bit (row 0, column 2) ...
     1 1 1
     0 1 0
     0 0 0
    after:
     1 0 1 <- ... has changed here
     1 1 1
     0 1 0
     0 0 0
    

    顺便说一句,您对矩阵的定义不起作用的原因是存在row 这个词。在该类型定义中没有 names 的位置,您只需要类型:

    tMatrix matrix(5, std::vector<bool>(5, false));
    

    我在上面的代码中添加了类似的行,已注释掉。如果你用它替换matrix 的当前声明,你会看到:

    before:
     0 0 0
     0 0 0
    after:
     0 0 1
     0 0 0
    

    (a) 除非您需要调整矩阵大小,否则最好使用std::arraystd::bitset

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多