Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.75/48: Рейтинг темы: голосов - 48, средняя оценка - 4.75
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50

Реализация вектора

10.01.2016, 11:24. Показов 10070. Ответов 80

Студворк — интернет-сервис помощи студентам
Добрый день. Нужно мне реализовать функции самому push_back та pop_back.
Моя реализация push_back. А от как реализовать pop_back я незнаю. Там нужно только удалить останий елемент. Но как это сделать? Подскиже.
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T, typename Allocator>
void Vector<T, Allocator>::push_back(const T& value)
{
    if (m_size == m_capacity)
    {
        const size_type capacity = 2 * m_capacity;
        pointer begin = m_allocator.allocate(capacity);
 
        UninitializedCopy(m_begin, m_begin + m_size, begin);
        deallocate();
 
        m_begin = begin;
        m_capacity = capacity;
    }
 
    m_allocator.construct(m_begin + m_size, value);
    ++m_size;
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
10.01.2016, 11:24
Ответы с готовыми решениями:

Реализация вектора
Всем доброго времени суток. Я сегодня уже обращался за помощью к форумчанам, но костыли не дремлют... Проблема: Есть класс User....

Реализация вектора
Здравствуйте друзья! Зашел в тупик после того как попытался реализовать структуру данных типа вектор своими силами. Допустим у нас есть...

Реализация вектора ссылок
Доброго времени суток, дорогие форумчане! Проблема в следующем: мне дано было задание сделать игру Го(кто не знает это что-то вроде...

80
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
12.01.2016, 15:36  [ТС]
Студворк — интернет-сервис помощи студентам
Croessmah,
я имею веду ерроры не выдает
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count > m_size)
    {
        if (count> m_capacity) 
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else 
    {
        deinitialize(m_begin, m_size - count);
        m_size = count;
    }
}
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
12.01.2016, 15:38
Цитата Сообщение от vvb2011 Посмотреть сообщение
я имею веду ерроры не выдает
а теперь сравним моё и Ваше:
C++
1
2
deinitialize(m_begin+count, m_size - count ) ;//моё чудо(с поправками в именах)
deinitialize(m_begin, m_size - count);//Ваше!
Разница очевидна? Вы уничтожаете элементы не там
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
12.01.2016, 15:43  [ТС]
Croessmah,
я убрал, так как вы в своем посту написали:
C++ (Qt)
1
deinitialize(m_begin+count, m_size - new_size ) ;//здесь взялся count? Оно здесь левое.
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
12.01.2016, 15:43
vvb2011, оно левое, потому что в моем примере нет имени count!
У меня оно new_size. И не должно было ничего компилироваться.
Но в силу того, что Вы поменяли код, всё стало компилироваться нормально.
А убрав его совсем, Вы стали удалять элементы сначала контейнера, а не с конца.
Но при этом всё остальное устраивается так, как будто удалили с конца.
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
12.01.2016, 15:45  [ТС]
Croessmah, new_size - мое count
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
12.01.2016, 15:47
vvb2011, код в студию! Компилируемый код программы! Гадать что там у Вас никому не интересно.
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
12.01.2016, 15:48  [ТС]
От мой компилированый код, но крешиться он:
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count > m_size)
    {
        if (count> m_capacity) 
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else 
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
12.01.2016, 15:51
Цитата Сообщение от vvb2011 Посмотреть сообщение
От мой компилированый код
Оно не скомпилируется!
Где всё остальное то?
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
12.01.2016, 15:57  [ТС]
Croessmah, но оно ероры ж не выдает)
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
12.01.2016, 15:59
Цитата Сообщение от vvb2011 Посмотреть сообщение
но оно ероры ж не выдает)
http://rextester.com/EXJ92957
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
13.01.2016, 14:26  [ТС]
Все что у меня есть:
C++ (Qt)
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
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count < m_size)
    {
        m_size = count;
        for (size_type index = count; index < allocator_size; index++)
            array[index] = T();
    }
    else if (count > m_size)
    {
        if (count> m_capacity) 
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else 
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
Добавлено через 7 минут

Добавлено через 2 минуты
Код всей програмы:
C++ (Qt)
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#pragma once
 
#include <cstddef>
#include <cassert>
#include <algorithm>
#include "Iterator.h"
 
template <typename T, typename Allocator>
class Vector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef typename Allocator::reference reference;
    typedef typename Allocator::const_reference const_reference;
    typedef typename Allocator::pointer pointer;
    typedef typename Allocator::const_pointer const_pointer;
 
    Vector();
    Vector(size_type count, const T& value = T());
    Vector(const_pointer begin, const_pointer end);
    Vector(const Vector& other);
    Vector& operator= (const Vector& other);
    ~Vector();
 
    size_type size() const;
    size_type capacity() const;
 
    reference operator[] (size_type index);
    const_reference operator[] (size_type index) const;
 
    void assign(size_type count, const T& value);
    allocator_type get_allocator() const;
 
    reference front();
    const_reference front() const;
 
    reference back();
    const_reference back() const;
 
    void push_back(const T& value);
    void pop_back();
 
    bool empty() const;
    void reserve(size_type size);
    void shrink_to_fit();
    void clear();
    void resize(size_type count, T value = T());
    
 
 
private:
    void unitialized_fill_n(pointer begin, size_type count, const T& value);
    void unitialized_copy(const_pointer begin, const_pointer end, pointer dest);
    void deinitialize(pointer begin, size_type count);
    void deallocate();
    void grow(size_type capacity);
    
    
private:
    Allocator m_allocator;
    size_type m_size;
    size_type m_capacity;
    pointer m_begin;
};
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector()
    : m_size(0)
    , m_capacity(0)
    , m_begin(nullptr)
{
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(size_type count, const T& value = T())
    : m_size(count)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const_pointer begin, const_pointer end)
    : m_size(end - begin)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(begin, end, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const Vector& other)
    : m_size(other.m_size)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>& Vector<T, Allocator>::operator= (const Vector& other)
{
    if (this != &other)
    {
        deallocate();
    
        m_size = other.m_size;
        m_capacity = m_size;
        m_begin = m_allocator.allocate(m_capacity);
 
        unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
    }
    return *this;
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::~Vector()
{
    deallocate();
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_fill_n(pointer begin, size_type count, const T& value)
{
    for (; count > 0; --count, ++begin)
        m_allocator.construct(begin, value);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_copy(const_pointer begin, const_pointer end, pointer dest)
{
    for (; begin != end; ++begin, ++dest)
        m_allocator.construct(dest, *begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deinitialize(pointer begin, size_type count)
{
    for (; count > 0; --count, ++begin)
        m_allocator.destroy(begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deallocate()
{
    deinitialize(m_begin, m_size);
    m_allocator.deallocate(m_begin, m_capacity);
 
    m_begin = nullptr;
    m_size = m_capacity = 0;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::size() const
{
    return m_size;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::capacity() const
{
    return m_capacity;
}
 
template<typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::operator[] (size_type index)
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T,Allocator>::operator[] (size_type index) const
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::assign(size_type count, const T& value)
{
    deallocate();
    
    m_size = count;
    m_capacity = m_size;
    m_begin = m_allocator.allocate(m_capacity);
    
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::allocator_type Vector<T, Allocator>::get_allocator() const
{
    return m_allocator;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::front()
{
    assert(m_size > 0);
    return m_begin[0];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::front() const
{
    assert(m_size > 0);
    return m_begin[0];
}
 
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::back() 
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::back() const
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::push_back(const T& value)
{
    if (m_size == m_capacity)
        grow(std::max(2 * m_capacity, 1u));
    m_allocator.construct(m_begin + m_size, value);
    ++m_size;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::pop_back()
{
    assert(m_size > 0);
    m_allocator.destroy(m_begin + (m_size - 1));
    --m_size;
}
 
template <typename T, typename Allocator>
bool Vector<T, Allocator>::empty() const
{
    return(m_begin == (m_begin + m_size));  
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::reserve(size_type capacity)
{
    if (capacity > m_capacity)
        grow(capacity);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::grow(size_type capacity)
{
    pointer begin = m_allocator.allocate(capacity);
 
    unitialized_copy(m_begin, m_begin + m_size, begin);
    deallocate();
 
    m_begin = begin;
    m_capacity = capacity;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::shrink_to_fit()
{
    grow(m_size);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::clear()
{
    deinitialize(m_begin, m_size);
    m_size = 0;
}
 
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count < m_size)
    {
        m_size = count;
        for (size_type index = count; index < allocator_size; index++)
            array[index] = T();
    }
    elseif (count > m_size)
    {
        if (count> m_capacity) 
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else 
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
 
 
template <typename T>
void vector<T>::resize(size_type count, T value = T())
{
    if (count < m_size)
    {
        m_size = count;
        for (size_type index = count; index < allocator_size; index++)
            array[index] = T();
    }
    else if (count > m_size) {
        if (count > m_size)
        {
            T* temp = new T[count];
            for (syze_type index = 0; index < m_size; index++)
            {
                temp[index] = array[index];
            }
            for (syze_type index = m_size; index < count; index++)
            {
                temp[index] = value;
            }
            m_size = count;
            delete[]array;
            array = new T[m_size];
            for (syze_type index = 0; index < count; index++)
            {
                array[index] = temp[index];
            }
            delete[]temp;
        }
        else if (count <= allocator_size) {
            for (syze_type index = m_size; index < count; index++)
            {
                array[index] = value;
            }
            m_size = count;
        }
    }
}
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
13.01.2016, 14:39
Нафига два разных resize'а?
C++
1
2
3
4
5
6
7
8
9
10
//а про это еще в посте #31 сказано, что лажа.
//Что оно здесь делает? Приведенный здесь код не соответствует тому, что приводили ранее.
//Как можно что-то обсуждать?
//На все посты, просьбы, советы Вам плевать!
    if (count < m_size)
    {
        m_size = count;
        for (size_type index = count; index < allocator_size; index++)
            array[index] = T();
    }
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
13.01.2016, 14:55  [ТС]
C++ (Qt)
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
pragma once
 
#include <iterator>
 
template <typename Category, typename T>
class Iterator
{
public:
    typedef T value_type;
    typedef T* pointer;
    typedef T& reference;
    typedef Category iterator_category;
 
protected:
    Iterator(){}
    Iterator(const Iterator&){}
    ~Iterator(){}
};
 
template <typename T>
class RandomAccessIterator : public Iterator<std::random_access_iterator_tag, T>
{
public:
    RandomAccessIterator()
        : m_current(nullptr)
    {}
 
    RandomAccessIterator(pointer current)
        : m_current(current)
    {}
 
    const reference operator* () const 
    {
        return *m_current;
    }
 
    reference operator* ()
    {
        return *m_current;
    }
 
    RandomAccessIterator& operator++ ()
    {
        ++m_current;
    }
 
    const RandomAccessIterator operator++ (int)
    {
        return RandomAccessIterator(m_current++);
    }
 
private:
    pointer m_current;
};
Добавлено через 33 секунды
C++ (Qt)
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#pragma once
 
#include <cstddef>
#include <cassert>
#include <algorithm>
#include "Iterator.h"
 
template <typename T, typename Allocator>
class Vector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef typename Allocator::reference reference;
    typedef typename Allocator::const_reference const_reference;
    typedef typename Allocator::pointer pointer;
    typedef typename Allocator::const_pointer const_pointer;
 
    Vector();
    Vector(size_type count, const T& value = T());
    Vector(const_pointer begin, const_pointer end);
    Vector(const Vector& other);
    Vector& operator= (const Vector& other);
    ~Vector();
 
    size_type size() const;
    size_type capacity() const;
 
    reference operator[] (size_type index);
    const_reference operator[] (size_type index) const;
 
    void assign(size_type count, const T& value);
    allocator_type get_allocator() const;
 
    reference front();
    const_reference front() const;
 
    reference back();
    const_reference back() const;
 
    void push_back(const T& value);
    void pop_back();
 
    bool empty() const;
    void reserve(size_type size);
    void shrink_to_fit();
    void clear();
    void resize(size_type count, T value = T());
    
 
 
private:
    void unitialized_fill_n(pointer begin, size_type count, const T& value);
    void unitialized_copy(const_pointer begin, const_pointer end, pointer dest);
    void deinitialize(pointer begin, size_type count);
    void deallocate();
    void grow(size_type capacity);
    
    
private:
    Allocator m_allocator;
    size_type m_size;
    size_type m_capacity;
    pointer m_begin;
};
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector()
    : m_size(0)
    , m_capacity(0)
    , m_begin(nullptr)
{
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(size_type count, const T& value = T())
    : m_size(count)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const_pointer begin, const_pointer end)
    : m_size(end - begin)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(begin, end, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const Vector& other)
    : m_size(other.m_size)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>& Vector<T, Allocator>::operator= (const Vector& other)
{
    if (this != &other)
    {
        deallocate();
    
        m_size = other.m_size;
        m_capacity = m_size;
        m_begin = m_allocator.allocate(m_capacity);
 
        unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
    }
    return *this;
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::~Vector()
{
    deallocate();
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_fill_n(pointer begin, size_type count, const T& value)
{
    for (; count > 0; --count, ++begin)
        m_allocator.construct(begin, value);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_copy(const_pointer begin, const_pointer end, pointer dest)
{
    for (; begin != end; ++begin, ++dest)
        m_allocator.construct(dest, *begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deinitialize(pointer begin, size_type count)
{
    for (; count > 0; --count, ++begin)
        m_allocator.destroy(begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deallocate()
{
    deinitialize(m_begin, m_size);
    m_allocator.deallocate(m_begin, m_capacity);
 
    m_begin = nullptr;
    m_size = m_capacity = 0;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::size() const
{
    return m_size;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::capacity() const
{
    return m_capacity;
}
 
template<typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::operator[] (size_type index)
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T,Allocator>::operator[] (size_type index) const
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::assign(size_type count, const T& value)
{
    deallocate();
    
    m_size = count;
    m_capacity = m_size;
    m_begin = m_allocator.allocate(m_capacity);
    
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::allocator_type Vector<T, Allocator>::get_allocator() const
{
    return m_allocator;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::front()
{
    assert(m_size > 0);
    return m_begin[0];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::front() const
{
    assert(m_size > 0);
    return m_begin[0];
}
 
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::back() 
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::back() const
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::push_back(const T& value)
{
    if (m_size == m_capacity)
        grow(std::max(2 * m_capacity, 1u));
    m_allocator.construct(m_begin + m_size, value);
    ++m_size;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::pop_back()
{
    assert(m_size > 0);
    m_allocator.destroy(m_begin + (m_size - 1));
    --m_size;
}
 
template <typename T, typename Allocator>
bool Vector<T, Allocator>::empty() const
{
    return(m_begin == (m_begin + m_size));  
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::reserve(size_type capacity)
{
    if (capacity > m_capacity)
        grow(capacity);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::grow(size_type capacity)
{
    pointer begin = m_allocator.allocate(capacity);
 
    unitialized_copy(m_begin, m_begin + m_size, begin);
    deallocate();
 
    m_begin = begin;
    m_capacity = capacity;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::shrink_to_fit()
{
    grow(m_size);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::clear()
{
    deinitialize(m_begin, m_size);
    m_size = 0;
}
 
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count < m_size)
    {
        m_size = count;
        for (size_type index = count; index < allocator_size; index++)
            array[index] = T();
    }
    elseif (count > m_size)
    {
        if (count> m_capacity) 
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else 
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
 
 
template <typename T>
void vector<T>::resize(size_type count, T value = T())
{
    if (count > m_size) {
        if (count > m_size)
        {
            T* temp = new T[count];
            for (syze_type index = 0; index < m_size; index++)
            {
                temp[index] = array[index];
            }
            for (syze_type index = m_size; index < count; index++)
            {
                temp[index] = value;
            }
            m_size = count;
            delete[]array;
            array = new T[m_size];
            for (syze_type index = 0; index < count; index++)
            {
                array[index] = temp[index];
            }
            delete[]temp;
        }
        else if (count <= allocator_size) {
            for (syze_type index = m_size; index < count; index++)
            {
                array[index] = value;
            }
            m_size = count;
        }
    }
}
Добавлено через 20 секунд
C++ (Qt)
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
#include "Allocator.h"
#include "Vector.h"
#include <iostream>
 
class A
{
public:
    ~A(){}
};
 
class B
{
private:
    ~B(){}
};
 
class C
{
protected:
    ~C(){}
};
 
class D : public C
{
public:
    ~D(){}
};
 
int main()
{
    Allocator<int> allocator;
 
    int* blockBegin = allocator.allocate(5);
    allocator.construct(blockBegin, 2);
    allocator.destroy(blockBegin);
    allocator.deallocate(blockBegin, 5);
 
    int array[] = {1, 3, 6, 8, 9, 2};
 
    Vector<int, Allocator<int>> v1;
    Vector<int, Allocator<int>> v2(5, 8);
    Vector<int, Allocator<int>> v3(3);
    Vector<int, Allocator<int>> v4(array, array + sizeof(array) / sizeof(array[0]));
    Vector<int, Allocator<int>> v5(v4);
 
    Vector<int, Allocator<int>>::size_type s5(v5.size());
    assert(v5.size() == 6);
 
    Vector<int, Allocator<int>>::size_type s1(v1.size());
 
    Vector<int, Allocator<int>>::size_type c2(v2.capacity());
    Vector<int, Allocator<int>>::size_type c3(v3.capacity());
    
    for (Vector<int, Allocator<int>>::size_type index  = 0; index < v4.size(); ++index)
        std::cout << "v4: " << v4[index] << "\n";
    
    std::cout << "\n";
 
    v4[2] = 9;
    for (Vector<int, Allocator<int>>::size_type index  = 0; index < v4.size(); ++index)
        std::cout << "v4: " << v4[index] << "\n";
 
    std::cout << "\n";
 
    v3.assign(8, 10);
    for (Vector<int, Allocator<int>>::size_type index  = 0; index < v3.size(); ++index)
        std::cout << "v3: " << v3[index] << "\n";
 
    Vector<int, Allocator<int>>::reference f(v2.front());
    f = 6456;
    for (Vector<int, Allocator<int>>::size_type index  = 0; index < v2.size(); ++index)
        std::cout << "v2: " << v2[index] << "\n";
 
    std::cout << "\n";
 
    Vector<int, Allocator<int>>::reference f1(v2.back());
    f1 = 6433;
    for (Vector<int, Allocator<int>>::size_type index  = 0; index < v2.size(); ++index)
        std::cout << "v2: " << v2[index] << "\n";
 
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.push_back(1);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
 
    A a;
 
    D* d = new D();
    delete d;
 
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.pop_back();
    std::cout << "v1, empty : " << v1.empty()<< "\n"; ;
    v1.push_back(1);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.reserve(4);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
 
    v1.clear();
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.shrink_to_fit();
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.resize(13);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    return 0;
}
Добавлено через 1 минуту
C++ (Qt)
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
#pragma once
 
#include <new>
#include <cstddef>
 
template <typename T>
class Allocator
{
public:
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
 
    pointer allocate(size_type number)
    {
        void* blockBegin = ::operator new (number * sizeof(T));
        return (pointer)blockBegin;
    }
    void deallocate(pointer blockBegin, size_type number)
    {
        ::operator delete(blockBegin);
    }
    void construct(pointer block, const_reference object)
    {
        ::new (block) T(object);
    }
    void destroy(pointer block)
    {
        block->~T();
    }
};
0
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
13.01.2016, 15:07  [ТС]
Код Vector
C++ (Qt)
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#pragma once
 
#include <cstddef>
#include <cassert>
#include <algorithm>
#include "Iterator.h"
 
template <typename T, typename Allocator>
class Vector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef typename Allocator::reference reference;
    typedef typename Allocator::const_reference const_reference;
    typedef typename Allocator::pointer pointer;
    typedef typename Allocator::const_pointer const_pointer;
 
    Vector();
    Vector(size_type count, const T& value = T());
    Vector(const_pointer begin, const_pointer end);
    Vector(const Vector& other);
    Vector& operator= (const Vector& other);
    ~Vector();
 
    size_type size() const;
    size_type capacity() const;
 
    reference operator[] (size_type index);
    const_reference operator[] (size_type index) const;
 
    void assign(size_type count, const T& value);
    allocator_type get_allocator() const;
 
    reference front();
    const_reference front() const;
 
    reference back();
    const_reference back() const;
 
    void push_back(const T& value);
    void pop_back();
 
    bool empty() const;
    void reserve(size_type size);
    void shrink_to_fit();
    void clear();
    void resize(size_type count, T value = T());
    
 
 
private:
    void unitialized_fill_n(pointer begin, size_type count, const T& value);
    void unitialized_copy(const_pointer begin, const_pointer end, pointer dest);
    void deinitialize(pointer begin, size_type count);
    void deallocate();
    void grow(size_type capacity);
    
    
private:
    Allocator m_allocator;
    size_type m_size;
    size_type m_capacity;
    pointer m_begin;
};
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector()
    : m_size(0)
    , m_capacity(0)
    , m_begin(nullptr)
{
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(size_type count, const T& value = T())
    : m_size(count)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const_pointer begin, const_pointer end)
    : m_size(end - begin)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(begin, end, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const Vector& other)
    : m_size(other.m_size)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>& Vector<T, Allocator>::operator= (const Vector& other)
{
    if (this != &other)
    {
        deallocate();
    
        m_size = other.m_size;
        m_capacity = m_size;
        m_begin = m_allocator.allocate(m_capacity);
 
        unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
    }
    return *this;
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::~Vector()
{
    deallocate();
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_fill_n(pointer begin, size_type count, const T& value)
{
    for (; count > 0; --count, ++begin)
        m_allocator.construct(begin, value);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_copy(const_pointer begin, const_pointer end, pointer dest)
{
    for (; begin != end; ++begin, ++dest)
        m_allocator.construct(dest, *begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deinitialize(pointer begin, size_type count)
{
    for (; count > 0; --count, ++begin)
        m_allocator.destroy(begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deallocate()
{
    deinitialize(m_begin, m_size);
    m_allocator.deallocate(m_begin, m_capacity);
 
    m_begin = nullptr;
    m_size = m_capacity = 0;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::size() const
{
    return m_size;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::capacity() const
{
    return m_capacity;
}
 
template<typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::operator[] (size_type index)
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T,Allocator>::operator[] (size_type index) const
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::assign(size_type count, const T& value)
{
    deallocate();
    
    m_size = count;
    m_capacity = m_size;
    m_begin = m_allocator.allocate(m_capacity);
    
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::allocator_type Vector<T, Allocator>::get_allocator() const
{
    return m_allocator;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::front()
{
    assert(m_size > 0);
    return m_begin[0];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::front() const
{
    assert(m_size > 0);
    return m_begin[0];
}
 
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::back() 
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::back() const
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::push_back(const T& value)
{
    if (m_size == m_capacity)
        grow(std::max(2 * m_capacity, 1u));
    m_allocator.construct(m_begin + m_size, value);
    ++m_size;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::pop_back()
{
    assert(m_size > 0);
    m_allocator.destroy(m_begin + (m_size - 1));
    --m_size;
}
 
template <typename T, typename Allocator>
bool Vector<T, Allocator>::empty() const
{
    return(m_begin == (m_begin + m_size));  
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::reserve(size_type capacity)
{
    if (capacity > m_capacity)
        grow(capacity);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::grow(size_type capacity)
{
    pointer begin = m_allocator.allocate(capacity);
 
    unitialized_copy(m_begin, m_begin + m_size, begin);
    deallocate();
 
    m_begin = begin;
    m_capacity = capacity;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::shrink_to_fit()
{
    grow(m_size);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::clear()
{
    deinitialize(m_begin, m_size);
    m_size = 0;
}
 
template <typename T, typename Allocator>
void Vector<typename T, typename Allocator>::resize(size_type count, T value = T())
{
    if (count > m_size)
    {
        if (count> m_capacity)
        {
            pointer begin = m_allocator.allocate(count);
            unitialized_copy(m_begin, m_begin + m_size, begin);
            size_t size = m_size;
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + count, count - m_size, value);
        m_size = count;
    }
    else
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
13.01.2016, 15:29
После исправления нескольких ошибок компиляции, оно всё-таки запустилось.
А Вас не удивляет работа Вашего reserve?
v1, size: 1, capacity: 1//До reserve
v1, size: 0, capacity: 4//после reserve
Причем элементы в контейнере при этом есть...
Вся проблема в grow, который допускает эту ошибку,
которая возникает в следствии кривого интерфейса deallocate

Добавлено через 11 минут
Я удивлен, как этого можно было не заметить.
Пример:
C++
1
2
3
4
5
6
7
8
    Vector<int, Allocator<int>> v1;
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.push_back(1);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.push_back(1);
    std::cout << "v1, size: " << v1.size() << ", capacity: " << v1.capacity() << "\n";
    v1.pop_back();
    std::cout << "v1, empty : " << v1.empty()<< "\n";
Элементы в вектор должны вроде бы добавляться, а видим такое:
v1, size: 0, capacity: 0//пусто, сказали добавить
v1, size: 1, capacity: 1//добавили, теперь 1, сказали еще добавить
v1, size: 1, capacity: 2//опять один? А резерв стал 2? прикольно..., давайте извлечем один и посмотрим
v1, empty : 1//контейнер пуст? Так мы ж два элемента добавляли...
Другими словами, всё что использует grow - багнутое!
1
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
13.01.2016, 15:46  [ТС]
Croessmah, но я же grow() не использую в своей функции resize() . а меня зараз именно работа этой функции интересует. С grow() переделаю
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
13.01.2016, 16:14
Лучший ответ Сообщение было отмечено vvb2011 как решение

Решение

попробуйте этот вектор (немного подправил grow и resize):
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#include <cstddef>
#include <cassert>
#include <algorithm>
#include "Iterator.h"
 
template <typename T, typename Allocator>
class Vector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef typename Allocator::reference reference;
    typedef typename Allocator::const_reference const_reference;
    typedef typename Allocator::pointer pointer;
    typedef typename Allocator::const_pointer const_pointer;
 
    Vector();
    Vector(size_type count, const T& value = T());
    Vector(const_pointer begin, const_pointer end);
    Vector(const Vector& other);
    Vector& operator= (const Vector& other);
    ~Vector();
 
    size_type size() const;
    size_type capacity() const;
 
    reference operator[] (size_type index);
    const_reference operator[] (size_type index) const;
 
    void assign(size_type count, const T& value);
    allocator_type get_allocator() const;
 
    reference front();
    const_reference front() const;
 
    reference back();
    const_reference back() const;
 
    void push_back(const T& value);
    void pop_back();
 
    bool empty() const;
    void reserve(size_type size);
    void shrink_to_fit();
    void clear();
    void resize(size_type count, T value = T());
 
 
 
private:
    void unitialized_fill_n(pointer begin, size_type count, const T& value  = T() );
    void unitialized_copy(const_pointer begin, const_pointer end, pointer dest);
    void deinitialize(pointer begin, size_type count);
    void deallocate();
    void grow(size_type capacity);
 
 
private:
    Allocator m_allocator;
    size_type m_size;
    size_type m_capacity;
    pointer m_begin;
};
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector()
    : m_size(0)
    , m_capacity(0)
    , m_begin(nullptr)
{
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(size_type count, const T& value)
    : m_size(count)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const_pointer begin, const_pointer end)
    : m_size(end - begin)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(begin, end, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::Vector(const Vector& other)
    : m_size(other.m_size)
    , m_capacity(m_size)
    , m_begin(m_allocator.allocate(m_capacity))
{
    unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>& Vector<T, Allocator>::operator= (const Vector& other)
{
    if (this != &other)
    {
        deallocate();
 
        m_size = other.m_size;
        m_capacity = m_size;
        m_begin = m_allocator.allocate(m_capacity);
 
        unitialized_copy(other.m_begin, other.m_begin + other.m_size, m_begin);
    }
    return *this;
}
 
template <typename T, typename Allocator>
Vector<T, Allocator>::~Vector()
{
    deallocate();
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_fill_n(pointer begin, size_type count, const T& value)
{
    for (; count > 0; --count, ++begin)
        m_allocator.construct(begin, value);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::unitialized_copy(const_pointer begin, const_pointer end, pointer dest)
{
    for (; begin != end; ++begin, ++dest)
        m_allocator.construct(dest, *begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deinitialize(pointer begin, size_type count)
{
    for (; count > 0; --count, ++begin)
        m_allocator.destroy(begin);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::deallocate()
{
    deinitialize(m_begin, m_size);
    m_allocator.deallocate(m_begin, m_capacity);
 
    m_begin = nullptr;
    m_size = m_capacity = 0;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::size() const
{
    return m_size;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::size_type Vector<T, Allocator>::capacity() const
{
    return m_capacity;
}
 
template<typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::operator[] (size_type index)
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T,Allocator>::operator[] (size_type index) const
{
    assert(index < m_size);
    return m_begin[index];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::assign(size_type count, const T& value)
{
    deallocate();
 
    m_size = count;
    m_capacity = m_size;
    m_begin = m_allocator.allocate(m_capacity);
 
    unitialized_fill_n(m_begin, m_size, value);
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::allocator_type Vector<T, Allocator>::get_allocator() const
{
    return m_allocator;
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::front()
{
    assert(m_size > 0);
    return m_begin[0];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::front() const
{
    assert(m_size > 0);
    return m_begin[0];
}
 
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::reference Vector<T, Allocator>::back()
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
typename Vector<T, Allocator>::const_reference Vector<T, Allocator>::back() const
{
    assert(m_size > 0);
    return m_begin[m_size - 1];
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::push_back(const T& value)
{
    if (m_size == m_capacity){
        grow((m_capacity == 0)?1:2 * m_capacity);
    }
 
    m_allocator.construct(m_begin + m_size, value);
    ++m_size;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::pop_back()
{
    assert(m_size > 0);
    m_allocator.destroy(m_begin + (m_size - 1));
    --m_size;
}
 
template <typename T, typename Allocator>
bool Vector<T, Allocator>::empty() const
{
    return(m_begin == (m_begin + m_size));
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::reserve(size_type capacity)
{
    if (capacity > m_capacity)
        grow(capacity);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::grow(size_type capacity)
{
    pointer begin = m_allocator.allocate(capacity);
 
    unitialized_copy(m_begin, m_begin + m_size, begin);
    size_t size = m_size ;
    deallocate();
    m_size = size ;
    m_begin = begin;
    m_capacity = capacity;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::shrink_to_fit()
{
    grow(m_size);
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::clear()
{
    deinitialize(m_begin, m_size);
    m_size = 0;
}
 
template <typename T, typename Allocator>
void Vector<T, Allocator>::resize(size_type count, T value)
{
    if (count > m_size)
    {
        if (count > m_capacity)
        {
            pointer begin = m_allocator.allocate(count);
            size_t size = m_size;
            unitialized_copy(m_begin, m_begin + m_size, begin);
            deallocate();
            m_capacity = count;
            m_size = size;
            m_begin = begin;
        }
        unitialized_fill_n(m_begin + m_size, count - m_size, value);
        m_size = count;
    }
    else
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}

меня зараз именно работа этой функции интересует.
тут всё просто:
C++
1
unitialized_fill_n(m_begin + m_size /*вместо count*/, count - m_size, value);
В принципе, после исправления grow можно сделать так:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T, typename Allocator>
void Vector<T, Allocator>::resize(size_type count, T value)
{
    if (count > m_size)
    {
        if (count > m_capacity)
        {
            grow(count) ;//Но я бы проверил лишний раз )))
        }
        unitialized_fill_n(m_begin + m_size, count - m_size, value);
        m_size = count;
    }
    else
    {
        deinitialize(m_begin + count, m_size - count);
        m_size = count;
    }
}
1
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
14.01.2016, 11:19  [ТС]
Продолжим, решил еще и итераторы поделать, я часть коду уже скидывал:
C++ (Qt)
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
#pragma once
 
#include <iterator>
 
template <typename Category, typename T>
class Iterator
{
public:
    typedef T value_type;
    typedef T* pointer;
    typedef T& reference;
    typedef Category iterator_category;
    typedef std::ptrdiff_t difference_type;
 
protected:
    Iterator(){}
    Iterator(const Iterator&){}
    ~Iterator(){}
};
 
template <typename T>
class RandomAccessIterator : public Iterator<std::random_access_iterator_tag, T>
{
public:
    RandomAccessIterator()
        : m_current(nullptr)
    {}
 
    RandomAccessIterator(pointer current)
        : m_current(current)
    {}
 
    reference operator* ()
    {
        return *m_current;
    }
 
    RandomAccessIterator& operator++ ()
    {
        ++m_current;
        return *this;
    }
 
    const RandomAccessIterator operator++ (int)
    {
        return RandomAccessIterator(m_current++);
    }
 
    RandomAccessIterator& operator-- ()
    {
        --m_current;
        return *this;
    }
    
    const RandomAccessIterator operator-- (int)
    {
        return RandomAccessIterator(m_current--);
    }
 
    bool operator== (const RandomAccessIterator& other) const 
    {
        return (m_current == other.m_current);
    }
 
    bool operator!= (const RandomAccessIterator& other) const
    {
        return (m_current != other.m_current);
    }
 
    RandomAccessIterator& operator+= (difference_type distance)
    {
        m_current += distance;
        return *this;
    }
 
    RandomAccessIterator& operator-= (difference_type distance)
    {
        m_current -= distance;
        return *this;
    }
 
    difference_type operator- (const RandomAccessIterator& other)
    {
        return (m_current - other.m_current);
    }
 
private:
    pointer m_current;
};
 
template <typename T>
RandomAccessIterator<T> operator+ (const RandomAccessIterator<T>& left, typename RandomAccessIterator<T>::difference_type distance)
{
    return (RandomAccessIterator<T>(left) += distance);
}
 
template <typename T>
RandomAccessIterator<T> operator- (const RandomAccessIterator<T>& left, typename RandomAccessIterator<T>::difference_type distance)
{
    return (RandomAccessIterator<T>(left) -= distance);
}
Решил в меине потестить функции:
1) Чтобы выводились значения с початка в конец и на оборот. С початка все ок выводиться а от с конца на 1 значении кряказябра стоит. Подскажите где бага?
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vector<char, Allocator<char>> v6;
    v6.reserve(4);
    v6.push_back('a');
    v6.push_back('b');
    v6.push_back('g');
    v6.push_back('c');
 
    Vector<char, Allocator<char>>::iterator it(v6.begin());
    Vector<char, Allocator<char>>::iterator itEnd(v6.end());
 
    for (; it != itEnd; ++it)
        std::cout << "it: " << *it << "\n";
 
    itEnd = v6.begin();
    for (it = v6.end(); it != itEnd; --it)
        std::cout << "it: " << *it << "\n";
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,038
Записей в блоге: 1
14.01.2016, 11:20
C++
1
2
itEnd = v6.begin()-1;//Соответствующие операторы перегрузить не забудьте
    for (it = v6.end()-1; it != itEnd; --it)
1
0 / 0 / 0
Регистрация: 09.01.2016
Сообщений: 50
14.01.2016, 12:17  [ТС]
мои операторы сравнения двох векторов:
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template< typename T, typename Allocator >
bool operator==(const vector<T, Allocator>& left, const vector<T, Allocator>& right)
{
    if (left.m_size() == right.m_size())
    {
        if (left.m_current == right.m_current)
            return true;
    }
    return false;
}
 
template< typename T, typename Allocator >
bool operator!=(const vector<T, Allocator>& left, const vector<T, Allocator>& right)
{
    if (left.m_size() != right.m_size())
    {
        if (left.m_current != right.m_current)
            return true;
    }
    return false;
}
Что еще нужно добавить для сравнения?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
14.01.2016, 12:17

Реализация собственного класса вектора
Создать абстрактный тип данных - класс вектор, который имеет указатель на float, число элементов и переменную состояния. Определить...

Реализация двусвязного списка на базе вектора
Дано задание реализовать двусвязный список на базе вектора. Насколько я понял, сам вектор реализовывать полностью не нужно, как и...

Реализация функций reserve и clear для вектора
Мне нужно самой написать реализацию. От что у меня есть: template&lt;typename T&gt; void Vector&lt;T&gt;::PopBack() { mVector.~T(); ...

Как обозначить значения внутри вектора для другого вектора итератором?
Например, в одном векторе есть числа 1, 3, 4. В другом векторе их 5: 25 95 45 65 75. Как сделать так, чтобы во втором векторе удалились...

Найти сколько элементов первого вектора совпадают с элементами второго вектора
#include &lt;iostream&gt; #include &lt;time.h&gt; #include &lt;vector&gt; #include &lt;set&gt; using namespace std; void main() { ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
60
Ответ Создать тему
Новые блоги и статьи
Море в объективе
kumehtar 06.07.2026
Хотел написать много проникновенных слов, но передумал. Оно само - говорит. Кто слышит тот слышит.
Оказывается, Unreal Engine позволяет качество на порядки выше, чем было в Lineedge
Etyuhibosecyu 05.07.2026
Жаль, конечно, что я не узнал об этом, пока Lineedge существовала, а то бы Noname2331 написал, что волки превращаются в пиксельную кашу, а я бы его попросил скачать какую-нибудь бриллиантовую или Pro. . .
Doom для терминала без стрельбы и монстров. 3D Raycasting на ascii.
dcc0 05.07.2026
Попросил нейронную сеть deepai. org написать рейкастинг 3D с библиотекой ncurses для Linux. Чтобы можно было ходить на стрелочки. Чтобы стены были отрисованы символами. Справилась. Первый вариант. . .
Установка статуса документа по условию
Maks 05.07.2026
Алгоритм из решения ниже реализован на нетиповом документе "НарядПутевка" разработанного в КА2. Задача: в табличной части "Материалы" документа при записи автоматически устанавливать статус. . .
Сезонность и суточность закисления почв
anaschu 04.07.2026
200 часов это все равно моловато. Есть ситуации, но нестандартные, когда смена происходит за 5 лет. Но обычно это 50 лет и более. Наверное, закисление почвы происходит сезонно в средней. . .
В чем ценность человеческого опыта в глобальном смысле?
kumehtar 03.07.2026
Возможно, ценность человека не в том, что он однажды достигает мудрости, а в том, что он становится носителем карты пути. Он знает не только истину, но и последовательность внутренних изменений,. . .
интеграция AnyLogic с самописным REST API и переход на Odoo
anaschu 03.07.2026
Успешная интеграция AnyLogic с самописным REST API и переход на промышленную Odoo WMS Сегодня проделал огромный путь от простой симуляции физических процессов до построения полноценной. . .
Поиск всех путей на ориентированном графе. Linux
dcc0 02.07.2026
Переработка старого кода из моей статьи. Через несколько переработок от PHP кода к C89 (надеюсь, 89). Но довольно запутанно получилось. Код для Linux. Но если убрать time и то, что с ним. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru