0

I am trying to initialize a simple vector with false values and then use it. I rellized the value is never 0 or 1, so I printed it. The result is that even in the beginning it has strange big values. I am compiling with g++ (GCC) 4.4.7. The question refers to printing only vector data of type bool.

What I did:

std::vector<bool> n;
int f = 0;
for(f = 0; f<10; f++)
    n.push_back(false);
for(f = 0; f<10; f++)
    printf("content of %d %d",f,n[f]);

What I got:

content of 0 30572784
content of 1 30572784
content of 2 30572784
content of 3 30572784
content of 4 30572784
content of 5 30572784
content of 6 30572784
content of 7 30572784
content of 8 30572784
content of 9 30572784

What am I doing wrong?

SuzLy
  • 133
  • 1
  • 10
  • 2
    What you're doing wrong is combining type-unsafe C library functions, like `printf()`, with C++ code. Do not use `printf` in C++. Use `std::cout`. – Sam Varshavchik Apr 21 '18 at 16:24
  • 1
    `printf` format string does not match input because `n[f]` is not an `int`. You should've got a corresponding compilation warning. – user7860670 Apr 21 '18 at 16:25
  • 2
    [`vector` is an odd beastie](http://en.cppreference.com/w/cpp/container/vector_bool). You might be better off [with a `std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset). – user4581301 Apr 21 '18 at 16:27
  • 1
    use cout + http://en.cppreference.com/w/cpp/io/manip/boolalpha if you want true/false instead of 1/0 – gchen Apr 21 '18 at 16:30
  • Possible duplicate of [Why does printf("%f",0); give undefined behavior?](https://stackoverflow.com/questions/38597274/why-does-printff-0-give-undefined-behavior) – xskxzr Apr 21 '18 at 17:10

2 Answers2

0

To initialize a bool vector, you can use fill constructor as given in documentation http://www.cplusplus.com/reference/vector/vector/vector/

std::vector<bool> n(10, false); (*)
Mesar ali
  • 1,832
  • 2
  • 16
  • 18
0

The problem is %d is for int(32bits), but to make a vector of bool more space efficient, vector<bool> is a specialized class that stores a bool as a single bit by using a proxy class. And, operator [] actually returns a reference of that proxy class (http://en.cppreference.com/w/cpp/container/vector_bool)

If you want to use printf, you'd need to cast it to a bool first

for(f = 0; f<10; f++)
    printf("content of %d %d",f,bool(n[f]));

Or, as others have mentioned in the Comments, use cout in C++.

cout << "content of " << f <<" " << n[f];

If you want to see true/false, you can also use std::boolalpha

cout << boolalpha << "content of " << f <<" " << n[f]; //will see true/false
gchen
  • 1,173
  • 1
  • 7
  • 12