i would like to make all the values in a std::vector true. I wrote 2 methods: the first one worked but the second did not. It tells me myproj.exe has triggered a breakpoint. Do you know what is the problem?
This one works:
void first(std::vector<bool>& vect, unsigned int n)
{
for (unsigned int i = 0; i < n; i++)
{
vect.push_back(true);
}
}
This one does not:
void secound(std::vector<bool>& vect, unsigned int n)
{
for(unsigned int i = 0; i < n; i++)
{
vect[i] = true; //crash here
}
}
You can use the following std::vector's overload:
vector(size_type count, const T& value, const Allocator& alloc = Allocator());
where the first argument is the size of the std::vector and the second argument is the initial value.
Full code:
#include <vector>
#include <iostream>
int main() {
std::vector<bool> v(10, true);
for (auto i : v) {
std::cout << std::boolalpha << i << std::endl;
}
return 0;
}
std::vector<bool> v(10, true); will create a vector with 10 boolean true values.
Check it out live.
If you want to reinitialize the std::vector, these are the following options:
std::fill like this std::fill(v.begin(), v.end(), true);std::vector::resize like this v.resize(10, true); if the std::vector is already initializedstd::vector::assign like this v.assign(10, true);In first case you call push_back which automatically increases size of vector.
In second case you trying to access vect[i] which does not exist as size of vector is 0.
Easiest way to fill vector here would be
vect = std::vector<bool>(n, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With