Skip to content

Commit

Permalink
Add util::algorithm::counter
Browse files Browse the repository at this point in the history
Signed-off-by: janus_wel <janus.wel.3@gmail.com>
  • Loading branch information
januswel committed Jun 20, 2010
1 parent cd25b3c commit e66b3c5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions header/algorithm.hpp
Expand Up @@ -23,6 +23,28 @@ namespace util {
void operator()(T* p) { delete p; }
};

// for std::generate() and std::generate_n()
template<typename T> class counter {
public:
typedef T count_type;

private:
count_type first, returned;
const count_type increment;

public:
counter(count_type first, count_type increment)
: first(first), increment(increment) {}
count_type operator()(void) {
returned = first;
first += increment;
return returned;
}

private:
counter& operator=(const counter& rhs);
};

// copy_if
template< typename InputIterator, typename OstreamIterator,
typename Predicate>
Expand Down
10 changes: 10 additions & 0 deletions sample/algorithm/main.cpp
Expand Up @@ -112,6 +112,16 @@ int main(const int argc, const char* const argv[]) {

std::cerr << std::endl;

// counter
// from 0, increment 1
std::generate_n(
std::ostream_iterator<unsigned int>(std::cout, "\n"), 10,
util::algorithm::counter<unsigned int>(0, 1));
// from 0.1, increment 0.3
std::generate_n(
std::ostream_iterator<double>(std::cout, "\n"), 10,
util::algorithm::counter<double>(0.1, 0.3));

return 0;
}

0 comments on commit e66b3c5

Please sign in to comment.