File: vector.cc

package info (click to toggle)
xmahjongg 3.5-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,060 kB
  • ctags: 1,317
  • sloc: cpp: 5,619; ansic: 3,451; sh: 330; makefile: 162
file content (74 lines) | stat: -rw-r--r-- 1,292 bytes parent folder | download | duplicates (2)
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
#include "vector.hh"

template <class T>
Vector<T>::Vector(const Vector<T> &o)
  : _l(0), _n(0), _cap(0)
{
  *this = o;
}

template <class T>
Vector<T>::~Vector()
{
  for (int i = 0; i < _n; i++)
    _l[i].~T();
  delete[] (unsigned char *)_l;
}

template <class T> Vector<T> &
Vector<T>::operator=(const Vector<T> &o)
{
  if (&o != this) {
    for (int i = 0; i < _n; i++)
      _l[i].~T();
    _n = 0;
    if (reserve(o._n)) {
      _n = o._n;
      for (int i = 0; i < _n; i++)
        new(velt(i)) T(o._l[i]);
    }
  }
  return *this;
}

template <class T> Vector<T> &
Vector<T>::assign(int n, const T &e)
{
  resize(0, e);
  resize(n, e);
  return *this;
}

template <class T> bool
Vector<T>::reserve(int want)
{
  if (want < 0)
    want = _cap > 0 ? _cap * 2 : 4;
  if (want <= _cap)
    return true;
  _cap = want;
  
  T *new_l = (T *)new unsigned char[sizeof(T) * _cap];
  if (!new_l) return false;
  
  for (int i = 0; i < _n; i++) {
    new(velt(new_l, i)) T(_l[i]);
    _l[i].~T();
  }
  delete[] (unsigned char *)_l;
  _l = new_l;
  return true;
}

template <class T>
void
Vector<T>::resize(int nn, const T &e)
{
  if (nn <= _cap || reserve(nn)) {
    for (int i = nn; i < _n; i++)
      _l[i].~T();
    for (int i = _n; i < nn; i++)
      new(velt(i)) T(e);
    _n = nn;
  }
}