[ create a new paste ] login | about

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

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

#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 & bi)
        : it(bi.it), pos(bi.pos), value(bi.value)
    {
    }
    
    bool operator == (const bit_iterator & rhs) const
    {
        return (it == rhs.it) && (pos == rhs.pos);
    }

    bool operator != (const bit_iterator & rhs) const
    {
        return !(*this == rhs);
    }

    bit_iterator & operator ++ ()
    {
        pos++;
        if (pos == CHAR_BIT*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
235032


Create a new paste based on this one


Comments: