Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
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).
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';
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
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.