Форум программистов, компьютерный форум, киберфорум
cortl
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  

ring container C++

Запись от cortl размещена 02.08.2019 в 13:38
Показов 2083 Комментарии 0

ring.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#ifndef RING_H
#define RING_H
 
#include <stdexcept>
 
template<class T>
class ring
{
    struct item
    {
        T *source;
        item *previous;
        item *next;
        item(T *source = nullptr) : source(source) {}
    };
public:
    class iterator
    {
        item *item_current;
    public:
        iterator(item *pointer = nullptr) : item_current(pointer) {}
        iterator(const iterator& other) : item_current(other.item_current) {}
        iterator operator++()
        {
            if(item_current != nullptr)
                item_current = item_current->next;
            return iterator(*this);
        }
        iterator operator--()
        {
            if(item_current != nullptr)
                item_current = item_current->previous;
            return iterator(*this);
        }
        iterator operator++(int)
        {
            iterator temp(*this);
            if(item_current != nullptr)
                item_current = item_current->next;
            return temp;
        }
        iterator operator--(int)
        {
            iterator temp(*this);
            if(item_current != nullptr)
                item_current = item_current->previous;
            return temp;
        }
        T& operator*() const { return *item_current->source; }
        friend class ring;
    };
private:
    iterator iterator_current = iterator();
    unsigned long long size = 0;
public:
    ~ring() { clear(); }
    void clear() { while(size) erase(); }
    iterator erase()
    {
        delete move();
        return iterator(iterator_current);
    }
    iterator get_iterator_current() { return iterator(iterator_current); }
    unsigned long long get_size() { return size; }
    iterator insert(T *source)
    {
        if (source == nullptr)
            throw std::runtime_error("ring.h: invalid source");
        item *temp = new item(source);
        if (size > 0)
        {
            temp->next = iterator_current.item_current;
            temp->previous = iterator_current.item_current->previous;
            iterator_current.item_current->previous->next = temp;
            iterator_current.item_current->previous = temp;
            iterator_current.item_current = temp;
        }
        else
        {
            iterator_current.item_current = temp;
            iterator_current.item_current->next = iterator_current.item_current;
            iterator_current.item_current->previous = iterator_current.item_current;
        }
        size++;
        return iterator(iterator_current);
    }
    iterator insert_next(T *source)
    {
        ++iterator_current;
        return insert(source);
    }
    T* move()
    {
        T *item_temp = nullptr;
        if (size > 1)
        {
            item_temp = iterator_current.item_current->source;
            iterator_current.item_current->next->previous = iterator_current.item_current->previous;
            iterator_current.item_current->previous->next = iterator_current.item_current->next;
            item *item_current_temp = iterator_current.item_current->next;
            delete iterator_current.item_current;
            iterator_current.item_current = item_current_temp;
            size--;
        }
        else if (size == 1)
        {
            item_temp = iterator_current.item_current->source;
            delete iterator_current.item_current;
            iterator_current.item_current = nullptr;
            size--;
        }
        else
            throw std::runtime_error("ring.h: moving from an empty container");
        return item_temp;
    }
};
 
#endif // RING_H
example:
Кликните здесь для просмотра всего текста

main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <stdexcept>
 
#include "ring.h"
 
using namespace std;
 
struct A
{
    int x;
    A(int x) : x(x) {}
};
 
int main()
{
    ring<A> r;
    ring<A>::iterator it;
 
    try { r.move(); }
    catch (exception& e) { cout << e.what() << endl; }
 
    try { r.insert(nullptr); }
    catch (exception& e) { cout << e.what() << endl; }
 
    int count = 0;
    while (count < 5)
        r.insert_next(new A(count++));
 
    cout << (*r.get_iterator_current()).x << endl;
    cout << (*--r.get_iterator_current()).x << endl;
    cout << (*++r.get_iterator_current()).x << endl;
 
    it = r.get_iterator_current();
    for (auto count = r.get_size(); count-->0;)
        cout << (*it++).x << " ";
    cout << endl;
 
    A *a = r.move();
    cout << (*a).x << endl;
    delete a;
 
    it = r.get_iterator_current();
    for (auto count = r.get_size(); count-->0;)
        cout << (*it--).x << " ";
    cout << endl;
 
    return 0;
}
output:
Bash
1
2
3
4
5
6
7
8
ring.h: moving from an empty container
ring.h: invalid source
4
3
0
4 0 1 2 3
4
0 3 2 1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
Саморегулирующийся социальный контракт для сервера cross-section.
Hrethgir 14.08.2026
С кодом конечно таких глубоких размышлений пока не было, впрочем я уже привык к алгоритмизации. Суть предмета записи: снова в диалоге с нейросетью (я взял пока себе ник для учётки админа - Rector). . . .
Часы электронные
Uhbif79 12.08.2026
Выкладываю программу часов. Программа позволяет: 1. Использовать системное время и дату, 2. Есть возможность вводить время и дату вручную. 3. Реализованы 2 будильника: начало и конец рабочего дня. . . .
Часы с будильником на основе класса QLCDNumber
Uhbif79 12.08.2026
Всем добрый день, выкладываю программу часов с будильником на основе класса QLCDNumber. Здесь я пробовал самостоятельно создавал классы, впервые столкнулся с видимостью переменной одного класса из. . .
Установка MinGW GCC 16.2 и CMake
8Observer8 10.08.2026
VK Видео: https:/ / vkvideo. ru/ video-240781534_456239017 YouTube: eY5-5PyI9NM Текстовая версия
Неделя из жизни имитационной модели склада: мои кривые руки растут, откуда надо
anaschu 10.08.2026
Неделя из жизни имитационной модели склада: как я почти написал неправильную логику и что с этим делать Работаю сейчас над учебно-рабочим проектом: строю в AnyLogic имитационную модель процессов. . .
Калькулятор для расчета родства
russiannick 07.08.2026
1. Задача: Создать калькулятор для расчета родства. Родственных связей существует 8 ступеней, такие как: p - отец P - мать q - муж Q - жена b - брат B - сестра s - сын S - дочь
Мир по моей воле
kumehtar 07.08.2026
Когда-то кажется, что всё просто. Ты весь такой светлый. Причиняешь добро. Борешься за справедливость в этом тёмном мире. Потом начинаешь замечать одну неприятную вещь. Почти каждый хороший. . .
Кредитный калькулятор
Maks 05.08.2026
Решение задачи по прикладной информатике средствами 1С. Задача: Напишите приложение-калькулятор, которое помогает рассчитывать параметры кредита для аннуитетного и дифференцированного видов. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru