Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active August 29, 2015 14:02
Show Gist options
  • Save dgodfrey206/cbfc45712e547913fb16 to your computer and use it in GitHub Desktop.
Save dgodfrey206/cbfc45712e547913fb16 to your computer and use it in GitHub Desktop.
An input stream iterator that constructs a vector from a line
#include <vector>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
template <
class Value,
class Container = std::vector<Value>,
class charT = char,
class traits = std::char_traits<charT>
>
class line_iterator
: public std::iterator<std::input_iterator_tag, std::vector<Value>>
{
public:
using value_type = Value;
using container_type = Container;
private:
std::basic_istream<charT, traits>* is_;
std::basic_string<charT, traits> line;
std::basic_istringstream<charT, traits> str;
container_type temp;
int count = -1;
public:
line_iterator(std::basic_istream<charT, traits>& is, int count = -1) noexcept
: is_(&is), count(count)
{ this->read(); }
constexpr line_iterator() noexcept : is_(nullptr)
{ }
constexpr line_iterator(const line_iterator& rhs) noexcept
: is_(rhs.is_), temp(rhs.temp), count(rhs.count)
{ };
constexpr container_type operator*() const noexcept
{
return std::move(temp);
}
line_iterator& operator++()
{
this->read();
return *this;
}
line_iterator operator++(int)
{
line_iterator copy(*this);
++*this;
return std::move(copy);
}
friend constexpr bool operator==(const line_iterator& lhs,
const line_iterator& rhs) noexcept
{
return lhs.is_ == rhs.is_;
}
friend constexpr bool operator!=(const line_iterator& lhs,
const line_iterator& rhs) noexcept
{
return !(lhs == rhs);
}
private:
void read()
{
this->temp.clear();
if (this->is_)
{
if (std::getline(*this->is_, this->line))
{
this->str.str(this->line);
if (this->count == -1)
this->temp.assign(std::istream_iterator<Value, charT, traits>{this->str}, {});
else if (0 <= this->count)
std::copy_n(
std::istream_iterator<Value, charT, traits>{this->str},
this->count,
std::back_inserter(this->temp));
}
if (!*this->is_)
this->is_ = nullptr;
this->str.clear();
}
}
};
template <
class Value,
class Container = std::vector<Value>,
class charT = char,
class traits = std::char_traits<charT>
>
line_iterator<Value, Container, charT, traits>
constexpr line_iter(std::basic_istream<charT, traits>& is, int count = -1) noexcept
{
return line_iterator<Value, Container, charT, traits>{is, count};
}
template<class Value>
constexpr line_iterator<Value> line_iter() noexcept
{
return line_iterator<Value>{};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment