Reputation: 1
i want too create a 2-D vector of Boolean type with Size n x n . but i don't want to use two for loop to assign false to every index instead of assign directly while creating this vector.
syntax is:- vector<vector<bool>> V(n,false)
but it gives me error
Upvotes: 0
Views: 2796
Reputation: 122133
There is a constructor that takes a count and an element, but false
is not a std::vector<bool>
. You want
std::vector<std::vector<bool>> V(n, std::vector<bool>(n,false) );
// |---- inner vectors ----|
Two disclaimer:
Use std::vector<bool>
with caution. It is not like other std::vector
s (see eg Alternative to vector<bool>).
A vector of vectors is rarely the best data structure. The power of a std::vector
is its data locality, however a std::vector<std::vector<T>>
does not have this feature (only elements of the inner vectors are contiguous).
Upvotes: 2
Reputation: 11
vector<vector> V(n,false)
this gives an error because you are not declaring size of each v[i] thus, it can not assign each of v[i][j] to false.
you can use vector<vector> v(n, vector (n, false));
Code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<vector<bool>> v(n, vector<bool> (n, false));
for(int i=0;i<n;i++)
{
for(int j=0;j<v[i].size();j++)
{
cout<<v[i][j]<<" ";
}
cout<<'\n';
}
}
Ans:
n=5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Upvotes: 1