简体   繁体   中英

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

I am wondering how I would initialize a matrix of 0s given that I want to use a <vector<vector> type and if it is possible to change the elements one by one in the boolean matrix the same as you would with an integer matrix (ex: matrix[row][col] = 1)

EDIT:

for example to make an NxN matrix I am trying:

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

this gives me the following error

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

for reference, I get the same error if I do something like this:

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

Sure you can. A vector of vector of boolean values may not necessarily be the most efficient means for this (a) , but it's certainly doable:

#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);
}

The output of that program shows that both aspects work, the initialisation nad the ability to change a single item:

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

As an aside, the reason why your definition of the matrix isn't working is because of the presence of the word row . There's no place for names in that type definition, you just need the types:

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

I've added a similar line to my code above, commented out. If you replace the current declaration of matrix with that, you'll see:

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

(a) Unless you need to resize the matrix, you may be better off with a std::array or std::bitset .

Your mistake was trying to name the inner vector passed to the outer vector 's constructor:

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

should just be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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