C++ customized iterator for C-style array

Xianbo QIAN
1 min readJan 29, 2020

--

std:: algorithms provides a nice zero-cost high level abstraction. It’s typically used together with std:: containers. However on embedded systems, std:: containers are two heavy to use as most of them requires dynamic allocation and flats the binary size.

Can std:: algorithm works on plain C-style array?

Yes! std:: algorithm is very generic. It works with almost any containers as long as the container can be visited with an iterator. So the question becomes, how to make a customized iterator for C-style array?

An iterator can be defined by inheriting from

std::iterator<std::input_iterator_tag, T>

and overrides ++,==, !=, * operators:

template <typename T>class ForwardIterator : public std::iterator<std::input_iterator_tag, T> {public:explicit ForwardIterator(T* p) : p_(p){};ForwardIterator& operator++() {p_++;return *this;};bool operator==(ForwardIterator other) const { return p_ == other.p_; }bool operator!=(ForwardIterator other) const { return p_ != other.p_; }T operator*() const { return *p_; }private:T* p_;};

Then you can use it as usual:

int data[] = {1, 2, 3};IntArray a(3, data);auto iter = std::find(a.begin(), a.end(), 1);

--

--

No responses yet