[英]Initialization of simple bool vector in c++ fails
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. 我认为该值永远不会为0或1,所以我将其打印出来。 The result is that even in the beginning it has strange big values. 结果是,即使在开始时,它也具有奇特的大价值。 I am compiling with g++ (GCC) 4.4.7. 我正在使用g ++(GCC)4.4.7进行编译。 The question refers to printing only vector data of type bool. 问题是仅打印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. 问题是%d
是用于int
(32位)的,但是要使bool
的vector
更节省空间, vector<bool>
是一个专用类,它通过使用代理类将bool作为单个位存储。 And, operator []
actually returns a reference of that proxy class ( http://en.cppreference.com/w/cpp/container/vector_bool ) 并且, operator []
实际上返回该代理类的引用( 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 如果要使用printf
,则需要先将其转换为布尔值
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++. 或者,正如其他人在评论中提到的那样,在C ++中使用cout
。
cout << "content of " << f <<" " << n[f];
If you want to see true/false, you can also use std::boolalpha
如果要查看是/ std::boolalpha
,也可以使用std::boolalpha
cout << boolalpha << "content of " << f <<" " << n[f]; //will see true/false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.