[ create a new paste ] login | about

Link: http://codepad.org/S1TT56PR    [ raw code | output | fork ]

k06a - C++, pasted on Jun 14:
// Bit_iterator demonstration

#include <iostream>
#include <fstream>
#include <iterator>

template<typename T>
class bit_iterator : public std::iterator<std::input_iterator_tag, T>
{
    std::istream_iterator<T> it;
    int pos;
    int value;

public:
    bit_iterator(std::istream_iterator<T> & it) : it(it), pos(0) {}
    bit_iterator(const bit_iterator & bit) : it(bit.it), pos(0) {}
    
    bool operator == (const bit_iterator & rhs) { return it == rhs.it; }
    bool operator != (const bit_iterator & rhs) { return it != rhs.it; }

    bit_iterator & operator ++ ()
    {
        pos++;
        if (pos == 8*sizeof(T))
        {
            ++it;
            pos = 0;
        }
        return *this;
    }

    bit_iterator operator ++ (int) 
    {
        bit_iterator tmp(*this);
        operator++();
        return tmp;
    }

    int & operator * ()
    {
        return value = ((*it) >> pos) & 1;
    }
};

int main(int argc, char * argv[])
{
    std::fstream file(argv[0], std::fstream::in | std::fstream::binary);

    std::istream_iterator<char> it_begin(file);
    std::istream_iterator<char> it_eof;

    bit_iterator<char> begin(it_begin);
    bit_iterator<char> end(it_eof);

    std::cout << std::count(begin, end, 1);
}


Output:
1
234659


Create a new paste based on this one


Comments: