我有以下代碼基本上需要一個向量並將其寫入文件,然後打開文件並將內容寫入不同的向量。運營商>>不喜歡矢量<bool>?
#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;
}
我注意到的是,該代碼編譯,並與當載體包含雙,int和長數據類型沒有問題的運行,但如果它更改爲布爾產生一個錯誤。這是我得到的錯誤消息:
../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))’
那麼,有沒有人知道爲什麼會發生這種情況?
謝謝
您發佈的代碼中沒有'vector'。 –
2013-05-09 19:37:23
我相信一個布爾變量的大小爲1位。所以一個轉變將無所作爲。 Check @Chris我錯了,當它清楚地說出字節時,將規範讀爲位。 – Nomad101 2013-05-09 19:37:32
@ Nomad101,變量必須至少有一個字節。 – chris 2013-05-09 19:37:55