CIN向布尔变量的矢量 [英] cin to vector of bools

查看:178
本文介绍了CIN向布尔变量的矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

#include <iostream>
#include <vector>

using namespace std;

int main(){
    vector <bool> v;
    cin >> v[0];
return 0;   
}

为什么我不能这样做呢?编译器将不能编译,但我有其他的变量类型的载体,它会工作得很好。这个有什么问题呢?

Why can't I do that? The compiler won't compile that, but I have other variable types in the vector, it will work just fine. What's the problem with this?

推荐答案

这是因为的std ::矢量&lt;布尔&GT; 是一个特例,不会像一个矢量在所有。这被普遍认为是在标准的一大缺陷。

It's because std::vector<bool> is a specialization and doesn't act like a vector at all. This is widely recognized to be a major flaw in the Standard.

为了节省内存,矢量&lt;&布尔GT; 存储每个元素作为单个位。但位不独立寻址,因此运算符[] 不能返回布尔和放大器;连接到位参考。相反,它返回矢量&lt;布尔&GT; ::参考 ...和 CIN 并没有提供的功能重载处理这一点。

In order to save memory, vector<bool> stores each element as a single bit. But bits aren't individually addressable, so operator[] can't return a bool& reference connected to a bit. Instead it returns vector<bool>::reference... and cin doesn't provide function overloads to deal with this.

(juanchopanza正确地指出你的载体没有一个元素为零。但是,即使它没有通过调整或其它机构,但事实上,运算符[] 不返回引用还是帮倒忙。)

(juanchopanza correctly points out that your vector didn't have an element zero. But even if it did via resize or other mechanism, the fact that operator[] doesn't return a reference still gets in the way.)

这篇关于CIN向布尔变量的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆