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?
要初始化布尔向量,可以使用文档http://www.cplusplus.com/reference/vector/vector/vector/中给出的fill构造函数
std::vector<bool> n(10, false); (*)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.