繁体   English   中英

我如何与<vector<vector<bool> &gt; 在 C++ 中?

[英]How do I work with <vector<vector<bool>> in C++?

我想知道我将如何初始化一个 0 矩阵,因为我想使用 <vector<vector> 类型,并且是否可以像使用整数矩阵一样在布尔矩阵中一个一个地更改元素(例如:矩阵[行][列] = 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)

你当然可以。 布尔值向量的向量可能不一定是最有效的方法(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 该类型定义中没有名称的位置,您只需要类型:

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

你的错误是试图命名传递给外部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))

暂无
暂无

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

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