gpt4 book ai didi

c++ - 运算符 >> 不喜欢 vector

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:26 25 4
gpt4 key购买 nike

我有以下代码,它基本上采用一个 vector 并将其写入一个文件,然后打开该文件并将内容写入另一个 vector 。

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<bool> q, p;
// ^^^^
q.resize(5, 0);
q[0] = 1;
q[2] = 1;
q[4] = 1;

ofstream ofile("file.log");

for (int i = 0; i<5; i++)
ofile <<q[i]<<" ";

ofile.close();

ifstream ifile("file.log");

p.resize(5);

int i = 0;
// vvvvvvvvvvvv
while(ifile>> p[i])
{
cout <<i<<"\t"<<p[i]<<endl;
i++;
}

ifile.close();

return 0;
}

我注意到,当 vector 包含 double、int 和 long 数据类型时,此代码编译和运行没有问题,但如果将其更改为 bool,则会产生错误。这是我收到的错误消息:

../src/timeexample.cpp:31: error: no match for ‘operator>>’ in ‘ifile >> p.std::vector<bool, _Alloc>::operator[] [with _Alloc = std::allocator<bool>](((long unsigned int)i))’

所以,有人知道为什么会这样吗?

谢谢

最佳答案

std::vector<bool> 专门用于提高空间效率。 operator[]将无法返回可寻址变量,因此它返回 std::vector<bool>::reference 代替代理对象。只需将它输入到一个临时变量并传输它:

bool b;
while (ifile >> b) {
p[i] = b;
cout <<i<<"\t"<<b<<endl;
i++;
}

关于c++ - 运算符 >> 不喜欢 vector<bool>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com