Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.87/75: Рейтинг темы: голосов - 75, средняя оценка - 4.87
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
1

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

18.05.2012, 20:37. Показов 14422. Ответов 37
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Для лабораторной работы нужно было написать свою реализацию классов вектор и строка.
Выкладываю что получилось, может, кому пригодится.
Кому не лень, пожалуйста, просмотрите код, скажите, что не так сделано, какие есть ошибки, чего не хватает и т.д.

mvector
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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#include <iostream>
#include <stdexcept>
#include <utility>
using std::rel_ops::operator!=;
using std::rel_ops::operator>;
using std::rel_ops::operator<=;
using std::rel_ops::operator>=;
 
template <typename T> 
class mvector
{
public:
    typedef size_t size_type;
    typedef T value_type;
    typedef T *pointer;
    typedef const T *const_pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef T* iterator;
    typedef const T* const_iterator; 
    explicit mvector();
    explicit mvector( size_type, const T& val = T() );
    mvector( const mvector<T>& );
    mvector( iterator, iterator );
    ~mvector();
    size_type size() const;
    size_type capacity() const;
    void resize( size_type, T = T() );
    void assign( iterator first, iterator last );
    void assign (size_type n, const T& u );
    void push_back( const T& );
    void pop_back();
    iterator erase( iterator );
    iterator erase( iterator, iterator );
    iterator insert( iterator, const T& );
    void insert( iterator, size_type, const T& );
    void insert( iterator, iterator, iterator );
    void clear();
    void swap( mvector<T>& ); 
    T& front();
    T& back();
    T& at( size_type );
    const T& at( size_type ) const;
    bool empty() const;
    const mvector& operator= ( const mvector& );
    const T& operator[] ( size_type ) const;
    T& operator[] ( size_type );
    iterator begin();
    const_iterator begin() const;
    iterator end();
    const_iterator end() const;
private:
    size_type _size;    
    size_type _capacity;    
    T *_arr;
};
 
template <typename T>
mvector<T>::mvector():
_size( 0 ), _capacity( 2*_size ), _arr( nullptr )
{
}   
 
template <typename T>
mvector<T>::mvector( size_type num, const T& val ):
_size( num ), _capacity( 2*_size ), _arr( new T[_capacity] )
{
    for ( size_type i = 0; i != _size; ++i )
        _arr[i] = val;
}
 
template <typename T>
mvector<T>::mvector( const mvector<T>& c ):
_size( c._size ), _capacity( c._capacity ), _arr( new T[_capacity] )
{
    for ( size_type i = 0; i != _size; ++i )
        _arr[i] = c._arr[i];
}
 
template <typename T>
mvector<T>::mvector( iterator start, iterator end ):
_size( end - start ), _capacity( 2*_size ), _arr( new T[_capacity] )
{
    for ( size_type i = 0; i != _size && start != end; ++i )
        _arr[i] = *start++;
}
 
template <typename T>
mvector<T>::~mvector()
{
    delete [] _arr;
}
 
template <typename T>
typename mvector<T>::size_type mvector<T>::size() const
{
    return _size;
}
 
template <typename T>
typename mvector<T>::size_type mvector<T>::capacity() const
{
    return _capacity;
}
 
template <typename T>
void mvector<T>::resize( size_type _new_size, T c )
{
    _capacity = 2 * _new_size;
    T *_new_arr = new T[_capacity];
    for ( size_type i = 0; i != std::min( _size, _new_size ); ++i )
        _new_arr[i] = _arr[i];
    for ( size_type i = std::min( _size, _new_size ); i != _new_size; ++i )
        _new_arr[i] = c;
 
    delete [] _arr;
    _size = _new_size;  
    _arr = _new_arr;
}
 
template <typename T>
void mvector<T>::assign( iterator first, iterator last )
{
    delete [] _arr;
    _size = last - first;
    _capacity = 2*_size;
    _arr = new T[_capacity];
    for ( size_type i = 0; i != _size && first != last; ++i )
        _arr[i] = *first++;
}
 
template <typename T>
void mvector<T>::assign( size_type n, const T& u )
{
    delete [] _arr;
    _size = n;
    _capacity = 2*_size;
    _arr = new T[_capacity];
    for ( size_type i = 0; i != _size; ++i )
        _arr[i] = u;
}
 
template <typename T>
void mvector<T>::push_back( const T& val )
{
    if ( _size == _capacity )
    {
        resize( _size + 1 );
        --_size;
    }
 
    _arr[_size++] = val;
}
 
template <typename T>
void mvector<T>::pop_back()
{
    if ( _size > 0 )
        --_size;
}
 
template <typename T>
typename mvector<T>::iterator mvector<T>::erase( iterator position )
{
    for ( iterator i = position; i != end(); ++i )
        *i = *( i + 1 );
    --_size;
    return position;
}
 
template <typename T>
typename mvector<T>::iterator mvector<T>::erase( iterator first, iterator last )
{
    size_type beg = first - begin();
    size_type end = last - begin();     
    size_type _new_size = _size - end + beg;
    size_type _new_capacity = 2 * _new_size;
 
    T *_new_arr = new T[_new_capacity];
 
    for ( size_type i = 0; i != beg; ++i )
        _new_arr[i] = _arr[i];
 
    for ( size_type i = beg, j = end; j != _size; ++i, ++j )
        _new_arr[i] = _arr[j];
 
    delete [] _arr;
 
    _size = _new_size;
    _capacity = _new_capacity;
    _arr = _new_arr;
    return begin() + beg;
}
 
template <typename T>
typename mvector<T>::iterator mvector<T>::insert( iterator position, const T& x )
{
    size_type tmp = position - begin();
    if ( _size + 1 > _capacity )
        resize( _size + 1 );
    else
        ++_size;
    position = begin() + tmp;
    for ( iterator i = end() - 1; i != position; --i )
        *i = *( i - 1 );
    *position = x;
    return position;
}
 
template <typename T>
void mvector<T>::insert( iterator position, size_type n, const T& x )
{
    size_type tmp = position - begin();
    if ( _size + n > _capacity )
        resize( _size + n );
    else
        _size += n;
    position = begin() + tmp;
    for ( iterator i = end() - 1; i != position + n - 1; --i )
        *i = *( i - n );
    for ( iterator i = position; i != position + n; ++i )
        *i = x;
}
 
template <typename T>
void mvector<T>::insert( iterator position, iterator first, iterator last )
{
    size_type tmp = position - begin();
    size_type n = last - first;
    if ( _size + n > _capacity )
        resize( _size + n );    
    else
        _size += n;
    position = begin() + tmp;
    for ( iterator i = end() - 1; i != position + n - 1; --i )
        *i = *( i - n );
    for ( iterator i = position; i != position + n && first != last; ++i )
        *i = *first++;
}
 
template <typename T>
void mvector<T>::clear() 
{
    delete [] _arr;
    _arr = nullptr;
    _size = 0;
    _capacity = 0;
}
 
template <typename T>
void mvector<T>::swap( mvector<T>& c ) 
{ 
    if ( *this != c )
    {
        std::swap( _size, c._size );
        std::swap( _capacity, c._capacity );
        std::swap( _arr, c._arr );
    }
}
 
template <typename T>
T& mvector<T>::at( size_type index )
{
    if ( index >= _size )
        throw std::out_of_range( "Expression: vector subscript out of range." );
    return _arr[index];
}
 
template <typename T>
const T& mvector<T>::at( size_type index ) const
{
    if ( index >= _size )
        throw std::out_of_range( "Expression: vector subscript out of range." );
    return _arr[index];
}
 
template <typename T>
T& mvector<T>::front()
{
    return at( 0 );
}
 
template <typename T>
T& mvector<T>::back()
{
    return at( _size - 1 );
}
 
template <typename T>
bool mvector<T>::empty() const
{
    return _size == 0;
}
 
template <typename T>
const mvector<T>& mvector<T>::operator= ( const mvector<T>& c )
{
    if ( *this != c )
    {
        _size = c._size;
        _capacity = c._capacity;
        delete [] _arr;
        _arr = new T[_capacity];
        for ( size_type i = 0; i != c._size; ++i )
            _arr[i] = c._arr[i];
    }
 
    return *this;
}
 
template <typename T>
const T& mvector<T>::operator[] ( size_type n ) const
{
    return _arr[n];
}
 
template <typename T>
T& mvector<T>::operator[] ( size_type n )
{   
    return _arr[n];
}
 
template <typename T>
bool operator== ( const mvector<T>& c1, const mvector<T>& c2 )
{
    if (c1.size() != c2.size())
        return false;
    else
    {
        for ( int i = 0; i != c1.size(); ++i )
            if ( c1[i] != c2[i] )
                return false;
    }
    return true;
}
 
template <typename T>
bool operator< ( const mvector<T>& c1, const mvector<T>& c2 )
{
    if (c1.size() != c2.size())
        return c1.size() < c2.size();
    else
    {
        for ( int i = 0; i != c1.size(); ++i )
            if ( c1[i] != c2[i] )
                return c1[i] < c2[i];
    }
    return false;
}
 
template <typename T>
typename mvector<T>::iterator mvector<T>::begin()
{
    return _arr; 
}
 
template <typename T>
typename mvector<T>::const_iterator mvector<T>::begin() const 
{
    return _arr; 
}
 
template <typename T>
typename mvector<T>::iterator mvector<T>::end() 
{
    return _arr + _size;
}
 
template <typename T>
typename mvector<T>::const_iterator mvector<T>::end() const 
{ 
    return _arr + _size; 
}


mstring
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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
#include <iostream>
#include <stdexcept>
#include <utility>
using std::rel_ops::operator!=;
using std::rel_ops::operator>;
using std::rel_ops::operator<=;
using std::rel_ops::operator>=;
 
class mstring
{
public:
    typedef size_t size_type;
    typedef char value_type;
    typedef char* pointer;
    typedef const char* const_pointer;
    typedef char& reference;
    typedef const char& const_reference;
    typedef char* iterator;
    typedef const char* const_iterator; 
    static const size_type npos = -1;
    mstring();
    mstring( const mstring& );
    mstring( size_type, char );
    mstring( const char* );
    mstring( const char* str, size_type length );
    mstring( const mstring&, size_type, size_type length = npos );
    mstring( iterator, iterator );
    ~mstring(); 
    friend bool operator== ( const mstring&, const mstring& );
    friend bool operator< ( const mstring&, const mstring& );
    char& at( size_type );
    const char& at( size_type ) const;
    char& operator[] ( size_type );
    const char& operator[] ( size_type ) const;
    mstring& operator= ( const mstring& );
    mstring& operator= ( const char* );
    mstring& operator= ( char );
    friend std::ostream& operator<< ( std::ostream&, const mstring& );
    friend std::istream& operator>> ( std::istream&, mstring& );
    mstring& operator+= ( const mstring& );
    mstring& operator+= ( const char* );
    mstring& operator+= ( const char ); 
    friend mstring operator+ ( const mstring&, const mstring& );
    friend mstring operator+ ( const char*, const mstring& );
    friend mstring operator+ ( char, const mstring& );
    friend mstring operator+ ( const mstring&, const char* );
    friend mstring operator+ ( const mstring&, char );
    mstring& append( const mstring& );
    mstring& append( const char* );
    mstring& append( const mstring&, size_type, size_type );
    mstring& append( const char*, size_type );
    mstring& append( size_type, char );
    mstring& append( iterator, iterator );
    mstring& assign( iterator, iterator );
    mstring& assign( const mstring& );
    mstring& assign( const char* );
    mstring& assign( const char*, size_type );
    mstring& assign( const mstring&, size_type, size_type );
    mstring& assign( size_type, char );
    iterator erase( iterator );
    iterator erase( iterator, iterator );
    mstring& erase( size_type index = 0, size_type num = npos );    
    iterator insert( iterator, char );
    mstring& insert( size_type, const mstring& );
    mstring& insert( size_type, const char* );
    mstring& insert( size_type, const mstring&, size_type, size_type );
    mstring& insert( size_type, const char*, size_type );
    mstring& insert( size_type, size_type, char );
    void insert( iterator, size_type, char );
    void insert( iterator, iterator, iterator );
    void insert( iterator, const_iterator, const_iterator );    
    size_type find( const mstring&, size_type index = 0 ) const;
    size_type find( const char*, size_type index = 0 ) const;
    size_type find( const char*, size_type, size_type ) const;
    size_type find( char, size_type index = 0 ) const;
    const char * data() const;
    char * c_str() const;
    mstring substr( size_type index = 0, size_type length = npos ) const;   
    size_type copy( char*, size_type, size_type index = 0 ) const;
    void resize( size_type );
    void push_back( const char& );
    void pop_back();
    void clear();
    void swap( mstring& );
    char& front();
    char& back();
    bool empty() const;
    int compare( const mstring& ) const;
    int compare( const char* ) const;
    int compare( size_type, size_type, const mstring& ) const;
    int compare( size_type, size_type, const char* s ) const;
    int compare( size_type, size_type, const mstring& str, 
        size_type, size_type ) const;
    int compare( size_type, size_type, const char*, size_type ) const;
    size_type length() const;
    size_type size() const;
    size_type capacity() const; 
    iterator begin();
    const_iterator begin() const;
    iterator end();
    const_iterator end() const;
private:
    size_type _len;
    size_type _capacity;
    char *_arr;
};
 
mstring::size_type _mstrlen( const char *str )
{ 
    mstring::size_type res = 0;
    while( *str++ )
        res++;
    return res;
}
 
char * _mstrcpy( char *dst, const char *src )
{
    char *res = dst;
    while( (*dst++ = *src++) );
    return res; 
}
 
char * _mstrncpy( char *dst, const char *src, mstring::size_type len )
{
    char *res = dst;
    while( len-- && ( *dst++ = *src++ ) );
    if ( *dst )
        *dst = '\0';
    return res; 
}
 
char * _mstrcat( char *str1, const char *str2 )
{
    char *res = str1;
    while( *str1 ) 
        str1++;
    while( (*str1++ = *str2++) );
    return res;
}
 
char * _mstrncat(char *str1, const char *str2, mstring::size_type count)
{
    char *res = str1;
    while(*str1) 
        str1++;
    while(count-- && (*str1++ = *str2++));
    if (*str1) 
        *str1 = '\0';
    return res;
}
 
int _mstrcmp( const char *str1, const char *str2 )
{
    while( ( unsigned char )*str1 == ( unsigned char )*str2 && *str1 )
    {
        str1++;
        str2++;
    }
    return ( int )*str1 - ( int )*str2;
}
 
int _mstrncmp( const char *str1, const char *str2, size_t count )
{
    while( --count && ( ( unsigned char )*str1 == ( unsigned char )*str2 ) && *str1 )
    {
        str1++;
        str2++;
    }
    return ( int )*str1 - ( int )*str2;
}
 
char * _mstrnset( char *str, int c, mstring::size_type n )
{
    char *res = str;
    if ( n > _mstrlen( str ) ) 
        n = _mstrlen( str );
    for( mstring::size_type i = 0; i != n; ++i )
        *str++ = c;
    return res;
}
 
char * _mstrstr( const char *str1, const char *str2 )
{
    mstring::size_type l1 = _mstrlen( str1 ), l2 = _mstrlen( str2 );
    for ( mstring::size_type i = 0; i != l1 - l2 + 1; ++i )
    {
        mstring::size_type f = 0;
        for ( mstring::size_type j = 0; j != l2; ++j )
        {
            if ( str1[i + j] == str2[j] ) 
                f++; 
            else 
                break;
        }
        if ( f == l2 ) 
            return ( char* const )str1 + i;
    }
    if ( l2 )
        return nullptr;
    else 
        return ( char* const )str1;
} 
 
char * _mstrnstr( const char *str1, const char *str2, mstring::size_type length1 )
{
    mstring::size_type l1 = length1, l2 = _mstrlen( str2 );
    for ( mstring::size_type i = 0; i != l1 - l2 + 1; ++i )
    {
        mstring::size_type f = 0;
        for ( mstring::size_type j = 0; j != l2; ++j )
        {
            if ( str1[i + j] == str2[j] ) 
                f++; 
            else 
                break;
        }
        if ( f == l2 ) 
            return ( char* const )str1 + i;
    }
    if ( l2 )
        return nullptr;
    else 
        return ( char* const )str1;
} 
 
mstring::mstring():
_len( 0 ), _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    *_arr = '\0';
}
 
mstring::mstring( const mstring& s ):
_len( s._len ), _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrcpy( _arr, s._arr );
}
 
mstring::mstring( size_type length, char ch ):
_len( length ), _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrnset( _arr, ch, length );
}
 
mstring::mstring( const char* str ):
_len( _mstrlen( str ) ), _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrcpy( _arr, str );
}
 
mstring::mstring( const char* str, size_type length ):
_len( std::min( length, _mstrlen( str ) ) ), 
    _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrncpy( _arr, str, std::min( length, _mstrlen( str ) ) );
}
 
mstring::mstring( const mstring& str, size_type index, size_type length ):
_len( std::min( length, str._len ) - index ), 
    _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrncpy( _arr, str._arr + index, std::min( length, str._len ) );
}
 
mstring::mstring( iterator start, iterator end ):
_len( end - start ), _capacity( 2*_len+1 ), _arr( new char[_capacity] )
{
    _mstrncpy( _arr, start, end - start );
}
 
mstring::~mstring()
{
    delete [] _arr;
}
 
bool operator== ( const mstring& c1, const mstring& c2 )
{
    return _mstrcmp( c1._arr, c2._arr ) == 0;
}
 
bool operator< ( const mstring& c1, const mstring& c2 )
{
    return _mstrcmp( c1._arr, c2._arr ) < 0;
}
 
char& mstring::at( size_type index )
{
    if ( index >= _len )
        throw std::out_of_range( "Expression: string subscript out of range." );
    return _arr[index];
}
 
const char& mstring::at( size_type index ) const
{
    if ( index >= _len )
        throw std::out_of_range( "Expression: string subscript out of range." );
    return _arr[index];
}
 
char& mstring::operator[] ( size_type index )
{
    return at( index );
}
 
const char& mstring::operator[]( size_type index ) const
{
    return at( index );
}
 
mstring& mstring::operator= ( const mstring& s )
{
    if ( *this != s )
    {
        _len = s._len;
        _capacity = s._capacity;
        delete [] _arr;
        _arr = new char[_capacity];
        _mstrcpy( _arr, s._arr );       
    }
 
    return *this;
}
 
mstring& mstring::operator= ( const char* s )
{
    if ( this->_arr != s )
    {
        _len = _mstrlen( s );
        _capacity = 2*_len+1;
        delete [] _arr;
        _arr = new char[_capacity];
        _mstrcpy( _arr, s );        
    }
 
    return *this;
}
 
mstring& mstring::operator= ( char ch )
{
    delete [] _arr;
    _len = 1;
    _capacity = 2*_len+1;
    _arr = new char[_capacity];
    *_arr = ch;
    *( _arr+1 ) = '\0';
    return *this;
}
 
std::ostream& operator<< ( std::ostream& out, const mstring& s )
{
    out << s._arr;
    return out;
}
 
std::istream& operator>> ( std::istream& in, mstring& s )
{
    char tmp[4096];
    in >> tmp;
    s = in ? tmp : mstring();
    return in;
}
 
mstring& mstring::operator+= ( const mstring& append )
{
    resize( _len + append._len + 1 );
    _mstrcat( _arr, append._arr );
    return *this;
}
 
mstring& mstring::operator+= ( const char* append )
{
    resize( _len + _mstrlen( append ) + 1 );
    _mstrcat( _arr, append );
    return *this;
}
 
mstring& mstring::operator+= ( const char append )
{
    push_back( append );
    return *this;
}
 
mstring operator+ ( const mstring& lhs, const mstring& rhs )
{
    mstring ret( lhs );
    ret += rhs;
    return ret;
}
 
mstring operator+ ( const char* lhs, const mstring& rhs )
{
    mstring ret( lhs );
    ret += rhs;
    return ret;
}
 
mstring operator+ ( char lhs, const mstring& rhs )
{
    mstring ret( 1, lhs );
    ret += rhs;
    return ret;
}
 
mstring operator+ ( const mstring& lhs, const char* rhs )
{
    mstring ret( lhs );
    ret += rhs;
    return ret;
}
 
mstring operator+ ( const mstring& lhs, char rhs )
{
    mstring ret( lhs );
    ret += rhs;
    return ret;
}
 
mstring& mstring::append( const mstring& str )
{
    _mstrcat( _arr, str._arr );
    return *this;
}
 
mstring& mstring::append( const char* str )
{
    _mstrcat( _arr, str );
    return *this;
}
 
mstring& mstring::append( const mstring& str, size_type index, size_type len )
{
    _mstrncat( _arr, str._arr + index, len );
    return *this;
}
 
mstring& mstring::append( const char* str, size_type num )
{
    _mstrncat( _arr, str, num );
    return *this;
}
 
mstring& mstring::append( size_type num, char ch )
{
    *this += mstring( num, ch );
    return *this;
}
 
mstring& mstring::append( iterator start, iterator end )
{
    _mstrncat( _arr, start, end - start );
    return *this;
}
 
mstring& mstring::assign( iterator start, iterator end )
{
    delete [] _arr;
    _len = end - start;
    _capacity = 2*_len+1;
    _arr = new char[_capacity];
    _mstrncpy( _arr, start, end - start );
    return *this;
}
mstring& mstring::assign( const mstring& str )
{
    *this = str;
    return *this;
}
mstring& mstring::assign( const char* str )
{
    *this = str;
    return *this;
}
 
mstring& mstring::assign( const char* str, size_type num )
{
    delete [] _arr;
    _len = num;
    _capacity = 2*_len+1;
    _arr = new char[_capacity];
    _mstrncpy( _arr, str, num );
    return *this;
}
 
mstring& mstring::assign( const mstring& str, size_type index, size_type len )
{
    delete [] _arr;
    _len = str._len;
    _capacity = 2*_len+1;
    _arr = new char[_capacity];
    _mstrncpy( _arr, str._arr + index, len );
    return *this;
}
 
mstring& mstring::assign( size_type num, char ch )
{
    *this = mstring(num, ch); 
    return *this;
}
 
mstring::iterator mstring::erase( iterator position )
{
    for ( iterator i = position; i != end(); ++i )
        *i = *( i + 1 );
    --_len;
    return position;
}
 
mstring::iterator mstring::erase( iterator first, iterator last )
{
    size_type beg = first - begin();
    size_type end = last - begin();     
    size_type _new_len = _len - end + beg;
    size_type _new_capacity = 2 * _new_len + 1;
 
    char *_new_arr = new char[_new_capacity];
 
    for ( size_type i = 0; i != beg; ++i )
        _new_arr[i] = _arr[i];
 
    for ( size_type i = beg, j = end; j != _len + 1; ++i, ++j )
        _new_arr[i] = _arr[j];
 
    delete [] _arr;
 
    _len = _new_len;
    _capacity = _new_capacity;
    _arr = _new_arr;
    return begin() + beg;
}
 
mstring& mstring::erase( size_type index, size_type num )
{
    num = std::min( num, _len - index );
    erase( begin() + index, begin() + index + num );
    return *this;
}
 
mstring::iterator mstring::insert( iterator p, char c )
{
    size_type tmp = p - begin();
    if ( _len + 1 > _capacity )
        resize( _len + 1 );
    else
        ++_len;
    p = begin() + tmp;
    for ( iterator i = end(); i != p; --i )
        *i = *( i - 1 );
    *p = c;
    return p;
}
 
void mstring::insert( iterator p, size_t n, char c )
{
    size_type tmp = p - begin();
    if ( _len + n > _capacity )
        resize( _len + n );
    else
        _len += n;
    p = begin() + tmp;
    for ( iterator i = end(); i != p + n - 1; --i )
        *i = *( i - n );
    for ( iterator i = p; i != p + n; ++i )
        *i = c;
}
 
void mstring::insert( iterator p, iterator first, iterator last )
{
    size_type tmp = p - begin();
    size_type n = last - first;
    if ( _len + n > _capacity )
        resize( _len + n ); 
    else
        _len += n;
    p = begin() + tmp;
    for ( iterator i = end(); i != p + n - 1; --i )
        *i = *( i - n );
    for ( iterator i = p; i != p + n && first != last; ++i )
        *i = *first++;
}
 
void mstring::insert( iterator p, const_iterator first, const_iterator last )
{
    size_type tmp = p - begin();
    size_type n = last - first;
    if ( _len + n > _capacity )
        resize( _len + n ); 
    else
        _len += n;
    p = begin() + tmp;
    for ( iterator i = end(); i != p + n - 1; --i )
        *i = *( i - n );
    for ( iterator i = p; i != p + n && first != last; ++i )
        *i = *first++;
}
 
mstring& mstring::insert ( size_t pos1, const mstring& str )
{
    insert( begin() + pos1, str.begin(), str.end() );
    return *this;
}
 
mstring& mstring::insert ( size_t pos1, const mstring& str, size_t pos2, size_t n )
{
    insert( begin() + pos1, str.begin() + pos2, str.begin() + n );
    return *this;
}
 
mstring& mstring::insert ( size_t pos1, const char* s, size_t n)
{
    insert( begin() + pos1, s, s + n );
    return *this;
}
 
mstring& mstring::insert ( size_t pos1, const char* s )
{
    insert( begin() + pos1, s, s + _mstrlen(s) );
    return *this;
}
 
mstring& mstring::insert ( size_t pos1, size_t n, char c )
{
    insert( begin() + pos1, n, c );
    return *this;
}
 
mstring::size_type mstring::find( const mstring& str, size_type index ) const
{
    pointer ptr = _mstrstr( _arr + index, str._arr );
    if (ptr != nullptr)
        return ptr - begin();
    else
        return npos;
}
 
mstring::size_type mstring::find( const char* str, size_type index ) const
{
    pointer ptr = _mstrstr( _arr + index, str );
    if (ptr != nullptr)
        return ptr - begin();
    else
        return npos;
}
 
mstring::size_type mstring::find( const char* str, size_type index,
    size_type length ) const
{
    pointer ptr = _mstrnstr( _arr + index, str , length);
    if (ptr != nullptr)
        return ptr - begin();
    else
        return npos;
}
 
mstring::size_type mstring::find( char ch, size_type index ) const
{
    for ( size_type i = index; i != _len; ++i )
    {
        if ( _arr[i] == ch ) 
            return i;
    }
    return npos;
}
 
const char * mstring::data() const
{
    return _arr;
}
 
char * mstring::c_str() const
{
    return _arr;
}
 
mstring mstring::substr( size_type index, size_type length ) const
{
    mstring res( this->_arr, index, length );
    return res;
}
 
mstring::size_type mstring::copy( char* str, size_type num, size_type index ) const
{
    _mstrncpy( str, _arr + index, num );
    return num - index;
}
 
void mstring::resize( size_type _new_len )
{
    _capacity = 2 * _new_len + 1;
    char *_new_arr = new char[_capacity];
    _mstrcpy( _new_arr, _arr );
    delete [] _arr;
    _len = _new_len;
    _arr = _new_arr;
}
 
void mstring::push_back( const char& val )
{
    if ( _len == _capacity )
    {
        resize( _len + 1 );
        --_len;
    }
 
    _arr[_len++] = val;
}
 
void mstring::pop_back()
{
    if ( _len > 0 )
        --_len;
}
 
void mstring::clear() 
{
    delete [] _arr;
    _len = 0;
    _capacity = 2*_len+1;
    _arr = new char[_capacity];
    *_arr = '\0';
}
 
void mstring::swap( mstring& c ) 
{ 
    if ( *this != c )
    {
        std::swap( _len, c._len );
        std::swap( _capacity, c._capacity );
        std::swap( _arr, c._arr );
    }
}
 
char& mstring::front()
{
    return at( 0 );
}
 
char& mstring::back()
{
    return at( _len - 2 );
}
 
bool mstring::empty() const
{
    return _len == 0;
}
 
int mstring::compare( const mstring& str ) const
{
    return _mstrcmp( this->_arr, str._arr );
}
 
int mstring::compare( const char* s ) const
{
    return _mstrcmp( this->_arr, s );
}
 
int mstring::compare( size_type pos1, size_type n1, const mstring& str ) const
{
    return _mstrncmp( this->_arr+pos1, str._arr, n1 - pos1 );
}
 
int mstring::compare( size_type pos1, size_type n1, const char* s ) const
{
    return _mstrncmp( this->_arr+pos1, s, n1 - pos1 );
}
 
int mstring::compare( size_type pos1, size_type n1,
    const mstring& str, size_type pos2, size_type n2 ) const
{
    return _mstrncmp( this->_arr+pos1, str._arr+pos2, 
        std::min( n1 - pos1, n2 - pos2 ) );
}
 
int mstring::compare( size_type pos1, size_type n1, 
    const char* s, size_type n2 ) const
{
    return _mstrncmp( this->_arr+pos1, s, std::min( n1 - pos1, n2 ) );
}
 
mstring::size_type mstring::length() const
{
    return _len;
}
 
mstring::size_type mstring::size() const
{
    return _len;
}
 
mstring::size_type mstring::capacity() const
{
    return _capacity;
}
 
mstring::iterator mstring::begin()
{
    return _arr; 
}
 
mstring::const_iterator mstring::begin() const 
{
    return _arr; 
}
 
mstring::iterator mstring::end() 
{
    return _arr + _len;
}
 
mstring::const_iterator mstring::end() const 
{ 
    return _arr + _len; 
}
7
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
18.05.2012, 20:37
Ответы с готовыми решениями:

Вектор классов. Реализация сортировки не работает
vector&lt;unique_ptr&lt;Figure&gt;&gt; figurki;// вектор классов фигур for (auto&amp;&amp; function : figurki) { ...

Создать иерархию классов вектор и безопасный вектор с проверкой выхода за пределы
Создать иерархию классов вектор и безопасный вектор с проверкой выхода за пределы. Безопасный...

Создать иерархию классов вектор и безопасный вектор с проверкой выхода за пределы
Создать иерархию классов вектор и безопасный вектор с проверкой выхода за пределы. Безопасный...

Создать иерархию классов вектор(longint) и безопасный вектор с проверкой выхода за пределы
Помогите не знаю как сделать! Создать иерархию классов вектор(longint) и безопасный вектор с...

37
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
12.07.2012, 21:26  [ТС] 21
Author24 — интернет-сервис помощи студентам
std::initializer_list добавлю, ток придется на liveworkspace сразу писать
ещеб неплохо добавить
reserve
shrink_to_fit
emplace
emplace_back
Цитата Сообщение от soon Посмотреть сообщение
Присутствуют мифические other.count, но отрабатывает корректно
с именами чет попутал. отрабатывает мож и корректно, но по сути там методы T && копия const T&, а вроде как с Rvalue Reference немного по другому надо работать. или по другому нужно только для конструктора и оператора копии?

Добавлено через 3 минуты
Цитата Сообщение от soon Посмотреть сообщение
Я считаю, что в конструкторе надо выделять столько памяти, сколько требуется. А в функциях вставки увеличивать m_capacity вдвое, если не хватает.
а как например с resize поступать? выделять только сколько требуется?

Добавлено через 7 минут
Цитата Сообщение от silent_1991 Посмотреть сообщение
softmob, когда я велосипедил (а велосипедил я тогда по максимуму, стараясь свести к минимуму использование стандартных средств), у меня получилось следующее.
я старался предоставить как можно больше интерфейса + попробовать сделать stl совместимым(получилось или нет без понятия)
вообще интересный пример, надо будет по изучать. особо в велосипедирование пока не ударялся хотя бы потому что особо не знаю как...
0
Эксперт С++
5055 / 3115 / 271
Регистрация: 11.11.2009
Сообщений: 7,044
12.07.2012, 21:33 22
softmob, насколько я помню (когда тестил этот класс), он получился stl-совместимым (скорее всего, только до некоторой степени, подробно не проверял). По крайней мере, std::sort и std::copy с ним работали.
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
12.07.2012, 21:44 23
Цитата Сообщение от softmob Посмотреть сообщение
но по сути там методы T && копия const T&, а вроде как с Rvalue Reference немного по другому надо работать. или по другому нужно только для конструктора и оператора копии?
Через std::move надо.

Цитата Сообщение от softmob Посмотреть сообщение
а как например с resize поступать? выделять только сколько требуется?
Полагаю, что да. Разумеется, все это просто размышления на тему "а как бы сделал я". Так что решать в любом случае вам.
0
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
13.07.2012, 17:08  [ТС] 24
добавил вроде все интерфейсные функции аналогичные std::vector
переделал выделение памяти, теперь резервирование происходит только при добавлении элементов или при использование reserve
подправил Rvalue Reference методы, ну и так по мелочи немного подправил
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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#include <iostream>
#include <algorithm>
#include <utility>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <cstddef>
 
#ifdef __GNUC__
#include <initializer_list>
#endif
 
using std::rel_ops::operator!=;
using std::rel_ops::operator>;
using std::rel_ops::operator<=;
using std::rel_ops::operator>=;
 
template <class T, class Allocator = std::allocator<T>> 
class mvector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T* iterator;
    typedef const T* const_iterator; 
    typedef std::reverse_iterator<iterator> reverse_iterator; 
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator; 
 
    explicit mvector( const Allocator& alloc = Allocator() ):
    m_size( 0 ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {} 
 
    mvector( size_type count, 
        const T& value,
        const Allocator& alloc = Allocator() ):
    m_size( count ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_fill_n( begin(), m_size, value );
    }
 
    explicit mvector( size_type count ):
    m_size( count ), m_capacity( m_size ), 
        m_alloc(), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_fill_n( begin(), m_size, T() );
    }
 
    template <class InputIterator>
    mvector( InputIterator first, InputIterator last, 
        const Allocator& alloc = Allocator() ):
    m_size( 0 ), m_capacity( 0 ),
        m_alloc( alloc ), m_arr( nullptr )
    { 
        typedef typename std::is_integral<InputIterator>::type Integral;
        m_initialize( first, last, Integral() );
    }
 
    mvector( const mvector& other ):
        m_size( other.m_size ), m_capacity( m_size ), 
        m_alloc( other.m_alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_copy( other.begin(), other.end(), begin() ); 
    }
 
    mvector( const mvector& other, const Allocator& alloc ):
        m_size( other.m_size ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_copy( other.begin(), other.end(), begin() ); 
    }
 
    mvector( mvector&& other ):
        m_size( 0 ), m_capacity( m_size ), 
        m_alloc(), m_arr( nullptr )
    {
        *this = std::move( other );
    }
 
    mvector( mvector&& other, const Allocator& alloc ):
        m_size( 0 ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( nullptr )
    {
        *this = std::move( other );
    }
 
    ~mvector()
    {
        clear();
        if ( m_arr && m_capacity )
            m_alloc.deallocate( m_arr, m_capacity );
        m_size = 0;
        m_capacity = 0; 
        m_arr = nullptr; 
    }
 
    mvector& operator= ( const mvector& other )
    {
        if ( this != &other )
            mvector( other ).swap( *this ); 
        return *this;
    }
 
    mvector& operator=( mvector&& other )
    {
        if ( this != &other )
            *this = std::move( other );
        return *this;
    }
 
    void assign( size_type count, const T& value )
    {
        mvector( count, value ).swap( *this ); 
    }
 
    template <class InputIterator>
    void assign( InputIterator first, InputIterator last )
    {
        mvector( first, last ).swap( *this ); 
    }
 
    allocator_type get_allocator() const
    {
        return m_alloc;
    }
 
    reference at( size_type pos )
    {
        if ( pos >= m_size )
            throw std::out_of_range( "vector subscript out of range." );
        return m_arr[pos];
    }
 
    const_reference at( size_type pos ) const
    {
        if ( pos >= m_size )
            throw std::out_of_range( "vector subscript out of range." );
        return m_arr[pos];
    }
 
    reference operator[] ( size_type pos )
    { 
        return m_arr[pos];
    }
 
    const_reference operator[] ( size_type pos ) const
    {
        return m_arr[pos];
    }
 
    reference front()
    {
        return *begin();
    }
 
    const_reference front() const
    {
        return *begin();
    }
 
    reference back()
    {
        return *( end() - 1 );
    }
 
    const_reference back() const
    {
        return *( end() - 1 );
    }
 
    pointer data()
    {
        return m_arr;
    }
 
    const_pointer data() const
    {
        return m_arr;
    }
 
    iterator begin()
    {
        return m_arr; 
    }
 
    const_iterator begin() const
    {
        return m_arr; 
    }
 
    const_iterator cbegin() const
    {
        return m_arr; 
    }
 
    iterator end()
    {
        return m_arr + m_size;
    }
 
    const_iterator end() const
    { 
        return m_arr + m_size; 
    }
 
    const_iterator cend() const
    { 
        return m_arr + m_size; 
    }
 
    reverse_iterator rbegin()
    {
        return reverse_iterator( end() );
    }
 
    const_reverse_iterator rbegin() const
    {
        return const_reverse_iterator( end() );
    }
 
    const_reverse_iterator crbegin() const
    {
        return const_reverse_iterator( end() );
    }
 
    reverse_iterator rend()
    {
        return reverse_iterator( begin() );
    }
 
    const_reverse_iterator rend() const
    {
        return const_reverse_iterator( begin() );
    }
 
    const_reverse_iterator crend() const
    {
        return const_reverse_iterator( begin() );
    }
 
    bool empty() const
    {
        return m_size == 0;
    }
 
    size_type size() const
    {
        return m_size;
    }
 
    size_type max_size() const
    {
        return size_type(-1) / sizeof(T);
    }
 
    void reserve( size_type size )
    {
        if ( capacity() < size ) 
        {
            size_type n = m_size;
            pointer newelements = m_alloc.allocate( size );
            std::uninitialized_copy( begin(), end(), newelements );
            clear();
            if ( m_arr && m_capacity )
                m_alloc.deallocate( m_arr, m_capacity );
            m_arr = newelements;
            m_size = n;
            m_capacity = size;
        }
    }
 
    size_type capacity() const
    {
        return m_capacity;
    }
 
    void shrink_to_fit()
    {
        if ( m_arr && size() != capacity() )
        {
            m_alloc.deallocate( end(), capacity() - size() );
            m_capacity = m_size;
        }
    }
 
    void clear() 
    {
        for ( iterator i = end(); i != begin(); )
            m_alloc.destroy(--i);
        m_size = 0; 
    }
 
    iterator insert( const_iterator pos, const T& value )
    {
        return m_fill_insert( pos, 1, value );
    }
 
    iterator insert( const_iterator pos, T&& value )
    {
        size_type n = std::distance( cbegin(), pos );       
        if ( size() + 1 > capacity() ) 
            reserve( 2 * ( size() + 1 ) ); 
        std::copy_backward( begin() + n, end(), end() + 1 ); 
        ++m_size;
        back() = std::move( value );        
        return begin() + n;
    }
 
    iterator insert( const_iterator pos, size_type count, const T& value )
    { 
        return m_fill_insert( pos, count, value );
    }
 
    template <class InputIterator>
    iterator insert( const_iterator pos, InputIterator first, InputIterator last)
    { 
        typedef typename std::is_integral<InputIterator>::type Integral;
        return m_insert_dispatch( pos, first, last, Integral() ); 
    }
 
    iterator erase( const_iterator pos )
    {
        size_type beg = std::distance( cbegin(), pos );
        if ( pos + 1 != cend() )
            std::copy( begin() + beg + 1, end(), begin() + beg );
        --m_size;
        destroy( end() );
        return begin() + beg;
    }
 
    iterator erase( const_iterator first, const_iterator last )
    {
        size_type size = std::distance( first, last );
        size_type beg = std::distance( cbegin(), first );
        iterator loc = std::copy( begin() + beg + size, end(), begin() + beg );
        for ( iterator i = end(); i != loc; )
            m_alloc.destroy(--i);
        return begin() + beg;
    }
 
    void push_back( const T& value )
    {
        insert( end(), value );
    }
 
    void push_back( T&& value )
    {
        insert( end(), std::move( value ) );
    }
 
    void pop_back()
    {
        if ( !empty() )
        {
            --m_size;
            m_alloc.destroy( end() );
        }
    }
 
    void resize( size_type count ) 
    {
        resize( count, T() );
    }
 
    void resize( size_type count, const value_type& value)
    { 
        if ( count < size() ) 
            erase( begin() + count, end() );
        else if ( count > size() )
            insert( end(), count - size(), value );
    } 
 
    void swap( mvector& other )
    { 
        if ( this != &other )
        {
            std::swap( m_size, other.m_size );
            std::swap( m_capacity, other.m_capacity );
            std::swap( m_alloc, other.m_alloc );
            std::swap( m_arr, other.m_arr );
        }
    }
#ifdef __GNUC__ 
public:
    mvector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() ): 
    mvector( init.begin(), init.end(), alloc )
    {}
 
    iterator insert( const_iterator pos, std::initializer_list<T> ilist )
    {
        return m_range_insert( pos, ilist.begin(), ilist.end() );
    }
 
    iterator emplace( const_iterator pos )
    {
        return pos;
    }
 
    template< class... Args > 
    iterator emplace( const_iterator pos, T&& value, Args&&... args )
    {
        return emplace( insert( pos, std::move(value ) ), args... );
    }
 
    void emplace_back()
    {}
 
    template< class... Args >
    void emplace_back( T&& value, Args&&... args )
    {
        push_back( std::move( value ) );
        emplace_back( args... );
    }
#endif
private:
    template <class Integer>
    void m_initialize( size_type count, const Integer& value, std::true_type ) 
    {
        m_size = count;
        m_capacity = m_size;
        m_arr = m_alloc.allocate( m_capacity );
        std::uninitialized_fill_n( begin(), m_size, value );
    }
 
    template <class InputIterator>
    void m_initialize( InputIterator first, InputIterator last, std::false_type ) 
    {
        m_size = std::distance( first, last );
        m_capacity = m_size;
        m_arr = m_alloc.allocate( m_capacity );
        std::uninitialized_copy( first, last, begin() ); 
    }
 
    template <class Integer>
    iterator m_insert_dispatch( const_iterator pos, size_type count,
        const T& value, std::true_type ) 
    {
        return m_fill_insert( pos, count, value );
    }
 
    template <class InputIterator>
    iterator m_insert_dispatch( const_iterator pos, InputIterator first, 
        InputIterator last, std::false_type )
    {
        return m_range_insert( pos, first, last );
    }
 
    iterator m_fill_insert( const_iterator pos, size_type count, const T& value )
    { 
        size_type n = std::distance( cbegin(), pos );
        if ( size() + count > capacity() ) 
            reserve( 2 * ( size() + count ) ); 
        std::copy_backward( begin() + n, end(), end() + count ); 
        std::fill( begin() + n, begin() + n + count, value );
        m_size += count;
        return begin() + n;
    }
 
    template <class InputIterator>
    iterator m_range_insert( const_iterator pos, 
        InputIterator first, InputIterator last ) 
    {
        size_type n = std::distance( cbegin(), pos );
        size_type count = std::distance ( first, last );
        if ( size() + count > capacity() )
            reserve( 2 * ( size() + count ) ); 
        std::copy_backward( begin() + n, end(), end() + count ); 
        std::copy( first, last, begin() + n ); 
        m_size += count;
        return begin() + n;
    }
private:
    size_type m_size; 
    size_type m_capacity; 
    allocator_type m_alloc;
    pointer m_arr;
};
 
template<class T, class Alloc>
bool operator== ( mvector<T, Alloc>& lhs, 
                 mvector<T, Alloc>& rhs )
{ 
    return (
        lhs.size() == rhs.size() 
        && 
        std::equal( lhs.begin(), lhs.end(), rhs.begin() )
        );
}
 
template <class T, class Alloc>
bool operator< ( mvector<T, Alloc>& lhs,
    mvector<T, Alloc>& rhs )
{
    return std::lexicographical_compare( lhs.begin(), lhs.end(), 
        rhs.begin(), rhs.end() );
}
 
template <class T, class Alloc>
void swap( mvector<T, Alloc> &lhs, 
          mvector<T, Alloc> &rhs )
{
    lhs.swap(rhs); 
}
 
#include <functional>
 
int main(void)
{
    mvector<int> v;
    std::function<int (int)> f = [&f](int n) { return !n ? 1 : n * f(n - 1); };
    std::generate_n( std::back_inserter(v), 10, [&]() { return f(rand() % 10); } ); 
    for (auto &x: v)
        std::cout << x << ' ';
    return 0;
}
http://liveworkspace.org/code/... da30f1442a
как считаете что здесь неплохо бы изменить?
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
13.07.2012, 17:43 25
C++
1
2
3
4
5
6
mvector( mvector&& other ):
    m_size( 0 ), m_capacity( m_size ), 
    m_alloc(), m_arr( nullptr )
{
    *this = std::move( other );
}
Не пойдет. Когда я говорил про std::move, я имел в виду это
C++
1
2
3
4
5
6
7
]mvector( mvector&& other ):
    m_size( std::move(other.m_size) ), m_capacity( std::move(other.m_capacity) ), 
    m_alloc( std::move(other.m_alloc) ), m_arr( std::move(other.m_arr) )
{
    other.m_size = 0;
    // etc...
}
А в operator=(&&) будет рекурсия.
Остальное не смотрел.
0
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
13.07.2012, 18:42  [ТС] 26
если исправить оператор переноса конструктор будет корректным...
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mvector& operator=( mvector&& other )
{
    if ( this != &other )
    {
        //нужно ли явно вызывать std::move?
        //other же и так &&, other.X разве не будет тоже &&? 
        //есть ли толк от std::move для POD?
        m_size = std::move( other.m_size );
        m_capacity = std::move( other.m_capacity );
        m_alloc = std::move( other.m_alloc );
        m_arr = std::move( other.m_arr );
        other.m_size = 0;   
        other.m_capacity = 0;
        other.m_arr = nullptr;
    }
    return *this;
}
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
13.07.2012, 19:19 27
Цитата Сообщение от softmob Посмотреть сообщение
если исправить оператор переноса конструктор будет корректным...
Да, но я не вижу смысла инициализировать переменные нулем, а затем для объекта вызывать оператор присваивания.

Добавлено через 7 минут
Цитата Сообщение от softmob Посмотреть сообщение
нужно ли явно вызывать std::move?
Да, иначе будет вызван конструктор копирования
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
#include <iostream>
#include <memory>
 
struct Foo
{
    Foo()
    {
 
    }
 
    Foo(const Foo&)
    {
        std::cout << "Foo(&)" << std::endl;
    }
 
    Foo(Foo&&)
    {
        std::cout << "Foo(&&)" << std::endl;
    }
};
 
class Bar
{
    Foo _f;
 
public:
    Bar()
    {
 
    }
 
    Bar(Bar&& b): _f(b._f)
    {
 
    }
};
 
int main()
{
    Bar b1;
    Bar b2(std::move(b1));
    return 0;
}
Цитата Сообщение от softmob Посмотреть сообщение
есть ли толк от std::move для POD?
Сомневаюсь. Поищу в стандарте. Или в статьях

Добавлено через 12 минут
Цитата Сообщение от soon Посмотреть сообщение
Сомневаюсь. Поищу в стандарте. Или в статьях
Объектов для перемещения/копирования нет, различий по времени тоже не должно быть.
0
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
17.07.2012, 00:21  [ТС] 28

Не по теме:

Цитата Сообщение от soon Посмотреть сообщение
Поищу в стандарте.
К сожалению, без знания английского от стандарта толку мало.


Добавлено через 4 минуты
Кстати как правильнее разбивать на файлы?
В литературе обычно предлагают стандартное разделение на .h + .cpp
Однако глянув на реализацию стандартной библиотеке, наблюдаешь в .h реализацию вместо объявлений + фалы без расширения содержащих в gcc инклуды, а в студии код реализации и инклюды зависимых фалов.
Как все же лучше и когда что использовать?
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
17.07.2012, 06:26 29
softmob, Все шаблоны должны подключаться(и определения, и реализация), поэтому я их разбиваю на hpp и ipp, а затем подключаю их в отдельный файл. Соответственно, при написании программы подключаю только его.
0
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
25.08.2012, 20:15  [ТС] 30
Цитата Сообщение от soon Посмотреть сообщение
разбиваю на hpp и ipp
что за ipp?

Добавлено через 1 минуту
немного переделал с использованием enable_if
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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#pragma once
#include <iostream>
#include <algorithm>
#include <utility>
#include <iterator>
#include <memory>
#include <type_traits>
#include <stdexcept>
#include <cstddef>
 
#ifdef __GNUC__
#include <initializer_list>
#endif
 
using std::rel_ops::operator!=;
using std::rel_ops::operator>;
using std::rel_ops::operator<=;
using std::rel_ops::operator>=;
 
template <class T, class Allocator = std::allocator<T>> 
class mvector
{
public:
    typedef T value_type;
    typedef Allocator allocator_type;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T* iterator;
    typedef const T* const_iterator; 
    typedef std::reverse_iterator<iterator> reverse_iterator; 
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator; 
 
    explicit mvector( const Allocator& alloc = Allocator() ):
    m_size( 0 ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {} 
 
    mvector( size_type count, 
        const T& value,
        const Allocator& alloc = Allocator() ):
    m_size( count ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_fill_n( begin(), m_size, value );
    }
 
    explicit mvector( size_type count ):
    m_size( count ), m_capacity( m_size ), 
        m_alloc(), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_fill_n( begin(), m_size, T() );
    }
 
    template <class InputIterator>
    mvector( InputIterator first, InputIterator last, 
        const Allocator& alloc = Allocator(),
        typename std::enable_if<!std::is_integral
        <InputIterator>::value>::type* = nullptr ):
    m_size( std::distance( first, last ) ), m_capacity( m_size ),
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    { 
        std::uninitialized_copy( first, last, begin() ); 
    }
 
    mvector( const mvector& other ):
        m_size( other.m_size ), m_capacity( m_size ), 
        m_alloc( other.m_alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_copy( other.begin(), other.end(), begin() ); 
    }
 
    mvector( const mvector& other, const Allocator& alloc ):
        m_size( other.m_size ), m_capacity( m_size ), 
        m_alloc( alloc ), m_arr( m_alloc.allocate( m_capacity ) )
    {
        std::uninitialized_copy( other.begin(), other.end(), begin() ); 
    }
 
    mvector( mvector&& other ):
        m_size( std::move(other.m_size) ), m_capacity( std::move(other.m_capacity) ), 
        m_alloc( std::move(other.m_alloc) ), m_arr( std::move(other.m_arr) )
    {
        other.m_size = 0;   
        other.m_capacity = 0;
        other.m_arr = nullptr;
    }
 
    mvector( mvector&& other, const Allocator& alloc ):
        m_size( std::move(other.m_size) ), m_capacity( std::move(other.m_capacity) ), 
        m_alloc( alloc ), m_arr( std::move(other.m_arr) )
    {
        other.m_size = 0;   
        other.m_capacity = 0;
        other.m_arr = nullptr;
    }
 
    ~mvector()
    {
        clear();
        if ( m_arr && m_capacity )
            m_alloc.deallocate( m_arr, m_capacity );
        m_size = 0;
        m_capacity = 0; 
        m_arr = nullptr; 
    }
 
    mvector& operator= ( const mvector& other )
    {
        if ( this != &other )
            mvector( other ).swap( *this ); 
        return *this;
    }
 
    mvector& operator= ( mvector&& other )
    {
        if ( this != &other )
        {
            m_size = std::move( other.m_size );
            m_capacity = std::move( other.m_capacity );
            m_alloc = std::move( other.m_alloc );
            m_arr = std::move( other.m_arr );
            other.m_size = 0;   
            other.m_capacity = 0;
            other.m_arr = nullptr;
        }
        return *this;
    }
 
    void assign( size_type count, const T& value )
    {
        mvector( count, value ).swap( *this ); 
    }
 
    template <class InputIterator>
    void assign( InputIterator first, InputIterator last )
    {
        mvector( first, last ).swap( *this ); 
    }
 
    allocator_type get_allocator() const
    {
        return m_alloc;
    }
 
    reference at( size_type pos )
    {
        if ( pos >= m_size )
            throw std::out_of_range( "vector subscript out of range." );
        return m_arr[pos];
    }
 
    const_reference at( size_type pos ) const
    {
        if ( pos >= m_size )
            throw std::out_of_range( "vector subscript out of range." );
        return m_arr[pos];
    }
 
    reference operator[] ( size_type pos )
    { 
        return m_arr[pos];
    }
 
    const_reference operator[] ( size_type pos ) const
    {
        return m_arr[pos];
    }
 
    reference front()
    {
        return *begin();
    }
 
    const_reference front() const
    {
        return *begin();
    }
 
    reference back()
    {
        return *( end() - 1 );
    }
 
    const_reference back() const
    {
        return *( end() - 1 );
    }
 
    pointer data()
    {
        return m_arr;
    }
 
    const_pointer data() const
    {
        return m_arr;
    }
 
    iterator begin()
    {
        return m_arr; 
    }
 
    const_iterator begin() const
    {
        return m_arr; 
    }
 
    const_iterator cbegin() const
    {
        return m_arr; 
    }
 
    iterator end()
    {
        return m_arr + m_size;
    }
 
    const_iterator end() const
    { 
        return m_arr + m_size; 
    }
 
    const_iterator cend() const
    { 
        return m_arr + m_size; 
    }
 
    reverse_iterator rbegin()
    {
        return reverse_iterator( end() );
    }
 
    const_reverse_iterator rbegin() const
    {
        return const_reverse_iterator( end() );
    }
 
    const_reverse_iterator crbegin() const
    {
        return const_reverse_iterator( end() );
    }
 
    reverse_iterator rend()
    {
        return reverse_iterator( begin() );
    }
 
    const_reverse_iterator rend() const
    {
        return const_reverse_iterator( begin() );
    }
 
    const_reverse_iterator crend() const
    {
        return const_reverse_iterator( begin() );
    }
 
    bool empty() const
    {
        return m_size == 0;
    }
 
    size_type size() const
    {
        return m_size;
    }
 
    size_type max_size() const
    {
        return size_type(-1) / sizeof(T);
    }
 
    void reserve( size_type size )
    {
        if ( capacity() < size ) 
        {
            size_type n = m_size;
            pointer newelements = m_alloc.allocate( size );
            std::uninitialized_copy( begin(), end(), newelements );
            clear();
            if ( m_arr && m_capacity )
                m_alloc.deallocate( m_arr, m_capacity );
            m_arr = newelements;
            m_size = n;
            m_capacity = size;
        }
    }
 
    size_type capacity() const
    {
        return m_capacity;
    }
 
    void shrink_to_fit()
    {
        if ( m_arr && size() != capacity() )
        {
            m_alloc.deallocate( end(), capacity() - size() );
            m_capacity = m_size;
        }
    }
 
    void clear() 
    {
        for ( iterator i = end(); i != begin(); )
            m_alloc.destroy(--i);
        m_size = 0; 
    }
 
    iterator insert( const_iterator pos, const T& value )
    {
        return insert( pos, 1, value );
    }
 
    iterator insert( const_iterator pos, T&& value )
    {
        size_type n = std::distance( cbegin(), pos );       
        if ( size() + 1 > capacity() ) 
            reserve( 2 * ( size() + 1 ) ); 
        std::copy_backward( begin() + n, end(), end() + 1 ); 
        ++m_size;
        back() = std::move( value );        
        return begin() + n;
    }
 
    iterator insert( const_iterator pos, size_type count, const T& value )
    { 
        size_type n = std::distance( cbegin(), pos );
        if ( size() + count > capacity() ) 
            reserve( 2 * ( size() + count ) ); 
        std::copy_backward( begin() + n, end(), end() + count ); 
        std::fill( begin() + n, begin() + n + count, value );
        m_size += count;
        return begin() + n;
    }
 
    template <class InputIterator>
    typename std::enable_if<!std::is_integral<InputIterator>::value, iterator>::
        type insert( const_iterator pos, InputIterator first, InputIterator last)
    { 
        size_type n = std::distance( cbegin(), pos );
        size_type count = std::distance ( first, last );
        if ( size() + count > capacity() )
            reserve( 2 * ( size() + count ) ); 
        std::copy_backward( begin() + n, end(), end() + count ); 
        std::copy( first, last, begin() + n ); 
        m_size += count;
        return begin() + n;
    }
 
    iterator erase( const_iterator pos )
    {
        size_type beg = std::distance( cbegin(), pos );
        if ( pos + 1 != cend() )
            std::copy( begin() + beg + 1, end(), begin() + beg );
        --m_size;
        destroy( end() );
        return begin() + beg;
    }
 
    iterator erase( const_iterator first, const_iterator last )
    {
        size_type size = std::distance( first, last );
        size_type beg = std::distance( cbegin(), first );
        iterator loc = std::copy( begin() + beg + size, end(), begin() + beg );
        for ( iterator i = end(); i != loc; )
            m_alloc.destroy(--i);
        return begin() + beg;
    }
 
    void push_back( const T& value )
    {
        insert( end(), value );
    }
 
    void push_back( T&& value )
    {
        insert( end(), std::move( value ) );
    }
 
    void pop_back()
    {
        if ( !empty() )
        {
            --m_size;
            m_alloc.destroy( end() );
        }
    }
 
    void resize( size_type count ) 
    {
        resize( count, T() );
    }
 
    void resize( size_type count, const value_type& value)
    { 
        if ( count < size() ) 
            erase( begin() + count, end() );
        else if ( count > size() )
            insert( end(), count - size(), value );
    } 
 
    void swap( mvector& other )
    { 
        if ( this != &other )
        {
            std::swap( m_size, other.m_size );
            std::swap( m_capacity, other.m_capacity );
            std::swap( m_alloc, other.m_alloc );
            std::swap( m_arr, other.m_arr );
        }
    }
#ifdef __GNUC__ 
public:
    mvector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() ): 
    mvector( init.begin(), init.end(), alloc )
    {}
 
    iterator insert( const_iterator pos, std::initializer_list<T> ilist )
    {
        return m_range_insert( pos, ilist.begin(), ilist.end() );
    }
 
    iterator emplace( const_iterator pos )
    {
        return pos;
    }
 
    template< class... Args > 
    iterator emplace( const_iterator pos, T&& value, Args&&... args )
    {
        return emplace( insert( pos, std::move(value ) ), args... );
    }
 
    void emplace_back()
    {} 
 
    template< class... Args >
    void emplace_back( T&& value, Args&&... args )
    {
        push_back( std::move( value ) );
        emplace_back( args... );
    }
#endif
private:
    size_type m_size; 
    size_type m_capacity; 
    allocator_type m_alloc;
    pointer m_arr; 
};
 
template<class T, class Alloc>
bool operator== ( const mvector<T, Alloc>& lhs, 
                 const mvector<T, Alloc>& rhs )
{ 
    return (
        lhs.size() == rhs.size() 
        && 
        std::equal( lhs.begin(), lhs.end(), rhs.begin() )
        );
}
 
template <class T, class Alloc>
bool operator< ( const mvector<T, Alloc>& lhs,
    const mvector<T, Alloc>& rhs )
{
    return std::lexicographical_compare( lhs.begin(), lhs.end(), 
        rhs.begin(), rhs.end() );
}
 
template <class T, class Alloc>
void swap( mvector<T, Alloc> &lhs, 
          mvector<T, Alloc> &rhs )
{
    lhs.swap(rhs); 
}
1
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
25.08.2012, 20:26 31
softmob, Расширение файла вообще не суть. .ipp используется к примеру бустом для переноса реализации шаблонных классов/функций туда, соответствено в .hpp подключается данный .ipp файл.

Добавлено через 2 минуты
C++
1
2
3
4
5
6
7
8
9
    mvector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() ): 
    mvector( init.begin(), init.end(), alloc )
    {}
 
    iterator insert( const_iterator pos, std::initializer_list<T> ilist )
    {
        return m_range_insert( pos, ilist.begin(), ilist.end() );
    }
Ммм. А зачем ilist копироваться? По ссылке константной логичнее же
0
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
25.08.2012, 20:53  [ТС] 32
объявления методов класс брал с http://en.cppreference.com/w/cpp/container/vector
там initializer_list по значению принимают
и кстати все примерах которые находил initializer_list тоже используется по значению
0
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
25.08.2012, 21:03 33
softmob, Да окей. Надо было мне в стандарт посмотреть, прежде чем писать.

Copying an initializer list does
not copy the underlying elements.
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
25.08.2012, 21:05 34
Первое, что бросилось в глаза - неправильная реализация emplace. Передавать argc... надо через move
C++
1
emplace_back(std::move(args)...); // на примере emplace_back
1
1255 / 705 / 359
Регистрация: 20.02.2010
Сообщений: 1,035
25.08.2012, 21:31  [ТС] 35
чет я так и не разберусь с Rvalue Reference
0
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
25.08.2012, 22:14 36
Пытался написать код, объясняющий r-ref, в итоге - запутался сам
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
#include <iostream>
#include <memory>
#include <functional>
 
void foo(const int&)
{
    std::cout << "foo(const int&)" << std::endl;
}
 
void foo(int&&)
{
    std::cout << "foo(int&&)" << std::endl;
}
 
void bar(const int& a)
{
    std::cout << "                   ";
    std::cout << "bar(const int&)" << std::endl;
    std::cout << "Without std::move: ";
    foo(a);
    std::cout << "With    std::move: ";
    foo(std::move(a));
}
 
void bar(int& a)
{
    std::cout << "                   ";
    std::cout << "bar(int&)" << std::endl;
    std::cout << "Without std::move: ";
    foo(a);
    std::cout << "With    std::move: ";
    foo(std::move(a));
}
 
void bar(int&& a)
{
    std::cout << "                   ";
    std::cout << "bar(int&&)" << std::endl;
    std::cout << "Without std::move: ";
    foo(a);
    std::cout << "With    std::move: ";
    foo(std::move(a));
}
 
int main()
{
    int a = 42;
    std::cout   << "/----------------------std::ref-----------------------/"
                << std::endl;
    bar(std::ref(a));
 
    std::cout   << "/---------------static_cast<const int&>---------------/"
                << std::endl;
    bar(static_cast<const int&>(a));
 
    std::cout   << "/----------------------std::cref----------------------/"
                << std::endl;
    bar(std::cref(a));
 
    std::cout   << "/----------------------std::move----------------------/"
                << std::endl;
    bar(std::move(a));
    
    return 0;
}
out
Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/----------------------std::ref-----------------------/
                   bar(int&)
Without std::move: foo(const int&)
With    std::move: foo(int&&)
/---------------static_cast<const int&>---------------/
                   bar(const int&)
Without std::move: foo(const int&)
With    std::move: foo(const int&)
/----------------------std::cref----------------------/
                   bar(int&&)
Without std::move: foo(const int&)
With    std::move: foo(int&&)
/----------------------std::move----------------------/
                   bar(int&&)
Without std::move: foo(const int&)
With    std::move: foo(int&&)

Удивило то, что const int& не кастуется в int&&. Из всего остального можно сделать вывод - если хотите, чтобы r-reference переменная продолжила свой путь по функциям именно как r-reference, то передавать ее надо исключительно через std::move.
1
2554 / 1319 / 178
Регистрация: 09.05.2011
Сообщений: 3,086
Записей в блоге: 1
27.08.2012, 07:07 37
Дубль 2.
Я несколько заблуждался в использовании в функции, принимающей r-ref, std::move, для последующей передачи аргумента, поскольку он может передаваться не только как r-reference, но и как l-reference.
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
#include <iostream>
#include <utility>
 
void overloaded(int&&)
{
    std::cout << "overloaded(int&&)" << std::endl;
}
 
void overloaded(int&)
{
    std::cout << "overloaded(int& )" << std::endl;
}
 
void first()
{
 
}
 
template <class T, class... Args>
void first(T&& var, Args&&... args)
{
    overloaded(std::forward<T>(var));
    first(std::forward<Args>(args)...);
}
 
void second()
{
 
}
 
template <class T, class... Args>
void second(T&& var, Args&&... args)
{
    overloaded(std::move(var));
    second(std::move(args)...);
}
 
int main()
{
    int a = 2;
    std::cout << "/--- with std::forward ---/" << std::endl;
    first(1, a);
    std::cout << "/----- with std::move ----/" << std::endl;
    second(1, a);
    std::cout << "/-------------------------/" << std::endl;
    return 0;
}
И пример передачи l-reference как r-reference(насколько я понимаю, это возможно только шаблонами или как показано ниже)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
using T = int&;
 
void foo(T&&)
{
 
}
 
int main()
{
    int a = 2;
    foo(a);
    return 0;
}
Добавлено через 11 минут
Ну и касаемо невозможности кастования c-ref в r-ref. Полагаю, все дело в этом
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
void foo(int&& a)
{
    a = 3;
    std::cout << a << std::endl;
}
 
void foo(const int& a)
{
    // a = 3; Error
}
 
int main()
{
    foo(2);
    return 0;
}
1
279 / 39 / 13
Регистрация: 11.10.2015
Сообщений: 405
25.12.2016, 23:10 38
Можно было в принципе через наследование определить:
C++
1
2
template <class InputIterator>
    typename std::enable_if_t<std::is_base_of<std::forward_iterator_tag, typename std::iterator_traits<InputIterator>::iterator_category>::value, iterator>
0
25.12.2016, 23:10
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.12.2016, 23:10
Помогаю со студенческими работами здесь

Вынести методы из классов Panel и PictureBox (явная реализация методов базовых абстрактных классов)
Тема: Множественное наследование. Явная реализация методов базовых абстрактных классов. Как...

Реализация отношения классов типа двунаправленная ассоциация, UML, порядок объявления классов, неполный класс
Доброго времени суток! Осваивая UML, решил реализовать отношение двунаправленной ассоциации по...

Как заполнить вектор на вектор классов
#include &lt;iostream&gt; #include &lt;vector&gt; class Num { private: int m_num; public: Num(int...

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


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

Или воспользуйтесь поиском по форуму:
38
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru