Warning: preg_grep(): Compilation failed: quantifier does not follow a repeatable item at offset 157 in /var/www/tg-me/post.php on line 75
Библиотека C/C++ разработчика | cpp, boost, qt | Telegram Webview: cppproglib/5836 -
Telegram Group & Telegram Channel
How to: Создание собственного итератора для контейнера

Периодически требуется реализовать интеграцию с STL алгоритмами. Для этого необходимо реализовать правильные API.

Проблема: Нужно создать контейнер, работающий с range-based for и STL.


✏️ Решение:

1️⃣ Реализуйте iterator traits
2️⃣ Определите begin() и end()
3️⃣ Поддержите const итераторы

#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++ разработчика #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/cppproglib/5836
Create:
Last Update:

How to: Создание собственного итератора для контейнера

Периодически требуется реализовать интеграцию с STL алгоритмами. Для этого необходимо реализовать правильные API.

Проблема: Нужно создать контейнер, работающий с range-based for и STL.


✏️ Решение:

1️⃣ Реализуйте iterator traits
2️⃣ Определите begin() и end()
3️⃣ Поддержите const итераторы

#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++ разработчика #буст

BY Библиотека C/C++ разработчика | cpp, boost, qt


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cppproglib/5836

View MORE
Open in Telegram


Библиотека C C разработчика | cpp boost qt Telegram | DID YOU KNOW?

Date: |

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

Библиотека C C разработчика | cpp boost qt from us


Telegram Библиотека C/C++ разработчика | cpp, boost, qt
FROM USA