Skip to content

Instantly share code, notes, and snippets.

@Jules-Baratoux
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jules-Baratoux/c6addd77280c764f593c to your computer and use it in GitHub Desktop.
Save Jules-Baratoux/c6addd77280c764f593c to your computer and use it in GitHub Desktop.
Homework #7 – IntegerRange::iterator
#pragma once
#include <iterator>
// Represents all integer values in the range [low, high).
// low must be <= high.
template <typename Int>
struct IntegerRange
{
struct iterator : public std::iterator<std::input_iterator_tag, Int>
{
iterator(const Int value) : value(value)
{
}
iterator(const iterator& other) : value(other.value)
{
}
bool operator!=(const iterator& other)
{
return value != other.value;
}
bool operator==(const iterator& other)
{
return value == other.value;
}
Int operator*(void)
{
return value;
}
iterator& operator++(void)
{
++value;
return *this;
}
iterator operator++(int)
{
iterator old(*this);
operator++();
return old;
}
private:
Int value;
};
IntegerRange(Int low, Int high) : low_(low), high_(high)
{
assert(low <= high);
}
const iterator begin() const
{
return iterator(low_);
}
const iterator end() const
{
return iterator(high_);
}
private:
const Int low_;
const Int high_;
};
#include <cassert>
#include <algorithm>
#include <iostream>
using std::cout;
#include <iterator>
using std::ostream_iterator;
#include "IntegerRange.hh"
int main(void)
{
// int and std::find
{
IntegerRange<int> range(-2, 3);
assert(std::find(range.begin(), range.end(), -2) == range.begin());
assert(std::find(range.begin(), range.end(), 3) == range.end());
}
// short and std::for_each
{
IntegerRange<short> range(-2, 3);
std::for_each(range.begin(), range.end(), [](short value)
{
static short expected = -2;
assert(value == expected++);
});
}
// long and std::count
{
IntegerRange<long> range(-2, 3);
assert(std::count(range.begin(), range.end(), -2) == 1);
assert(std::count(range.begin(), range.end(), 3) == 0);
}
// unsigned and std::equal
{
IntegerRange<unsigned> range(2, 9);
IntegerRange<unsigned> same(2, 9);
IntegerRange<unsigned> different(1, 9);
assert(std::equal(range.begin(), range.end(), same.begin()) == true);
assert(std::equal(range.begin(), range.end(), different.begin()) == false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment