Created
August 17, 2016 15:35
-
-
Save cjxgm/4cdd5fd435b1bd1ccd7b460f6bf9afd1 to your computer and use it in GitHub Desktop.
Capped back insert iterator (C++)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <utility> // std::forward | |
#include <iterator> // std::iterator, std::output_iterator_tag | |
template <class Container> | |
struct capped_back_insert_iterator final: std::iterator<std::output_iterator_tag, void, void, void, void> | |
{ | |
capped_back_insert_iterator(Container & con, int cap) | |
: con{con}, capacity{cap}, size{0} {} | |
capped_back_insert_iterator & operator * () { return *this; } | |
capped_back_insert_iterator & operator ++ () { return *this; } | |
capped_back_insert_iterator & operator ++ (int) { return *this; } | |
template <class T> | |
capped_back_insert_iterator & operator = (T && x) | |
{ | |
if (size < capacity) { | |
size++; | |
con.push_back(std::forward<T>(x)); | |
} | |
return *this; | |
} | |
private: | |
Container & con; | |
int capacity; | |
int size; | |
}; | |
template <class Container> | |
auto capped_back_inserter(Container & con, int cap) | |
{ | |
return capped_back_insert_iterator<Container>{con, cap}; | |
} | |
//////////////////// test //////////////////// | |
#include <vector> | |
#include <algorithm> | |
#include <iostream> | |
int main() | |
{ | |
std::vector<int> a{1, 2, 3, 4, 5, 6, 7, 8}; | |
std::vector<int> b; | |
std::copy(begin(a), end(a), capped_back_inserter(b, 3)); | |
for (auto x: b) std::cerr << x << "\n"; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment