ipl*_*uto 2 c++ boolean file vector ifstream
我有以下代码,它基本上采用向量并将其写入文件,然后打开文件并将内容写入不同的向量.
#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;
}
Run Code Online (Sandbox Code Playgroud)
我注意到的是,当向量包含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))’
Run Code Online (Sandbox Code Playgroud)
那么,有谁知道为什么会这样?
谢谢
std::vector<bool>专注于提高空间效率.operator[]将无法返回可寻址变量,因此它返回一个std::vector<bool>::reference代理对象.只需将其输入临时变量并传输即可:
bool b;
while (ifile >> b) {
p[i] = b;
cout <<i<<"\t"<<b<<endl;
i++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |