tg-me.com/cppproglib/5836
Last Update:
Периодически требуется реализовать интеграцию с STL алгоритмами. Для этого необходимо реализовать правильные API.
Проблема: Нужно создать контейнер, работающий с range-based for и STL.
#include <iterator>
#include <algorithm>
#include <iostream>
template<typename T>
class CircularBuffer {
T* data;
size_t capacity_;
size_t size_;
size_t head_ = 0;
public:
explicit CircularBuffer(size_t capacity)
: data(new T[capacity]), capacity_(capacity), size_(0) {}
~CircularBuffer() { delete[] data; }
// Iterator class
class iterator {
T* ptr;
size_t capacity;
size_t index;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
iterator(T* ptr, size_t capacity, size_t index)
: ptr(ptr), capacity(capacity), index(index) {}
reference operator*() { return ptr[index % capacity]; }
pointer operator->() { return &ptr[index % capacity]; }
iterator& operator++() {
++index;
return *this;
}
iterator operator++(int) {
iterator tmp = *this;
++index;
return tmp;
}
bool operator==(const iterator& other) const {
return index == other.index;
}
bool operator!=(const iterator& other) const {
return !(*this == other);
}
};
void push(const T& item) {
data[(head_ + size_) % capacity_] = item;
if (size_ < capacity_) {
++size_;
} else {
++head_;
head_ %= capacity_;
}
}
iterator begin() { return iterator(data, capacity_, head_); }
iterator end() { return iterator(data, capacity_, head_ + size_); }
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
};
int main() {
CircularBuffer<int> buffer(5);
// Заполняем буфер
for (int i = 1; i <= 7; ++i) {
buffer.push(i);
}
// Range-based for работает!
for (const auto& item : buffer) {
std::cout << item << " ";
}
std::cout << std::endl;
// STL алгоритмы работают!
auto it = std::find(buffer.begin(), buffer.end(), 5);
if (it != buffer.end()) {
std::cout << "Found: " << *it << std::endl;
}
}
Частые ошибки: Не реализовать все необходимые operator для итератора.
💡 Совет: Правильные итераторы делают ваш контейнер first-class citizen в ST.
Библиотека C/C++ разработчика #буст