Search code examples
c++filevectorbooleanifstream

Operator >> doesn't like vector<bool>?


I have the following code which basically takes a vector and writes it to a file, and then opens the file and writes the content into a different 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;
}

What I noticed is that this code compiles and runs with no problem when the vector contains double, int, and long data types, but produces an error if it is changed to bool. This is the error message that I get:

../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))’

So, does anyone know why this happens?

Thank you


Solution

  • std::vector<bool> is specialized to have space efficiency. operator[] wouldn't be able to return an addressable variable, so it returns a std::vector<bool>::reference proxy object instead. Just input it to a temporary variable and transfer it:

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