Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill vector with true value

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        
    }
}
like image 969
cain Avatar asked Aug 11 '26 21:08

cain


2 Answers

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:

  1. use std::fill like this std::fill(v.begin(), v.end(), true);
  2. use std::vector::resize like this v.resize(10, true); if the std::vector is already initialized
  3. use std::vector::assign like this v.assign(10, true);
like image 81
NutCracker Avatar answered Aug 14 '26 10:08

NutCracker


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);
like image 23
Tarek Dakhran Avatar answered Aug 14 '26 12:08

Tarek Dakhran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!