I want to run a simple program in C++ in which there are two vectors - one is a std::vector<int>
and the other is a std::vector<bool>
of equal length. The value of the boolean vector at an index decides whether the value of the integer vector will be printed or not. Here is a copy of the program I am trying to run:
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> arr{1, 2, 3, 4, 5};
vector<bool> b(true, arr.size());
for(int i=0; i<arr.size(); i++){
if(b[i])
cout<<arr[i]<<endl;
}
return 0;
}
The above program runs as expected. But there is an Address Boundary Error encountered when I change the values from true
to false
in the std::vector initialization line. Precisely, the error is:
fish: Job 1, './test_vector_bool' terminated by signal SIGSEGV (Address boundary error)
I am already aware of some of the major pitfalls of using vector<bool>
from these threads:
What I gathered from these threads is we should not be using reference for vector<bool>
in cpp. But all I need to know is why is the vector with true
working and initialization with false
failing?
Aucun commentaire:
Enregistrer un commentaire