Home > Back-end >  How do you initialize a vector bool matrix in C ?
How do you initialize a vector bool matrix in C ?

Time:06-29

I come from a mostly Java background (I use Java for algorithm challenges) , but I'm trying to practice my C . This is my solution to a problem in which I need a vector bool matrix.

class Solution {
public:
    string longestPalindrome(string s) {
        
        string result = "";
        
        vector<vector<bool>> dp(s.length());
        
        for (int i = s.length() - 1; i >= 0; i--) {
            
            for (int j = 0; j < s.length(); j  ) {
                
                dp[i][j] = s[i] == s[j] && (j - i < 3 || dp[i   1][j - 1]);
                
                if (dp[i][j] && (result.empty() || j - i   1 > result.length())) {
                    
                    result = s.substr(i, j   1);
                }
                
            }
        }
        
        return result;
    }
};

This solution works in Java actually. In Java, I just do:

boolean[][] = new boolean[s.length()][s.length()];

As you see, I want to create a bool matrix in which the rows and columns are all of size s.length(). Unfortunately in my C solution, the compiler gives me this error:

Line 86: Char 2: runtime error: store to null pointer of type 'std::_Bit_type' (aka 'unsigned long') (stl_bvector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c  /9/bits/stl_bvector.h:95:2

I am certain the problem is how I am initializing the vector bool matrix. What can I do to solve this issue ? How do I initialize the vector matrix ?

CodePudding user response:

You can initialize a vector matrix like this:

std::vector<std::vector<type>> vec_name{ rows, std::vector<type>(cols) };

..which in your case is:

std::vector<std::vector<bool>> dp{ s.length(), std::vector<bool>(s.length()) };
  • Related