简单的Int容器类
1: #ifndef INTARRAY_H
2: #define INTARRAY_H
3:
4: #include <assert.h> // for assert()
5:
6: class IntArray
7: {
8: private:
9: int m_nLength;
10: int *m_pnData;
11:
12: public:
13: IntArray()
14: {
15: m_nLength = 0;
16: m_pnData = 0;
17: }
18:
19: IntArray(int nLength)
20: {
21: m_pnData = new int[nLength];
22: m_nLength = nLength;
23: }
24:
25: ~IntArray()
26: {
27: delete[] m_pnData;
28: }
29:
30: void Erase()
31: {
32: delete[] m_pnData;
33: // We need to make sure we set m_pnData to 0 here, otherwise it will
34: // be left pointing at deallocated memory!
35: m_pnData = 0;
36: m_nLength = 0;
37: }
38:
39: int& operator[](int nIndex)
40: {
41: assert(nIndex >= 0 && nIndex < m_nLength);
42: return m_pnData[nIndex];
43: }
44:
45: // Reallocate resizes the array. Any existing elements will be destroyed.
46: // This function operates quickly.
47: void Reallocate(int nNewLength)
48: {
49: // First we delete any existing elements
50: Erase();
51:
52: // If our array is going to be empty now, return here
53: if (nNewLength<= 0)
54: return;
55:
56: // Then we have to allocate new elements
57: m_pnData = new int[nNewLength];
58: m_nLength = nNewLength;
59: }
60:
61: // Resize resizes the array. Any existing elements will be kept.
62: // This function operates slowly.
63: void Resize(int nNewLength)
64: {
65: // If we are resizing to an empty array, do that and return
66: if (nNewLength <= 0)
67: {
68: Erase();
69: return;
70: }
71:
72: // Now we can assume nNewLength is at least 1 element. This algorithm
73: // works as follows: First we are going to allocate a new array. Then we
74: // are going to copy elements from the existing array to the new array.
75: // Once that is done, we can destroy the old array, and make m_pnData
76: // point to the new array.
77:
78: // First we have to allocate a new array
79: int *pnData = new int[nNewLength];
80:
81: // Then we have to figure out how many elements to copy from the existing
82: // array to the new array. We want to copy as many elements as there are
83: // in the smaller of the two arrays.
84: if (m_nLength > 0)
85: {
86: int nElementsToCopy = (nNewLength > m_nLength) ? m_nLength : nNewLength;
87:
88: // Now copy the elements one by one
89: for (int nIndex=0; nIndex < nElementsToCopy; nIndex++)
90: pnData[nIndex] = m_pnData[nIndex];
91: }
92:
93: // Now we can delete the old array because we don't need it any more
94: delete[] m_pnData;
95:
96: // And use the new array instead! Note that this simply makes m_pnData point
97: // to the same address as the new array we dynamically allocated. Because
98: // pnData was dynamically allocated, it won't be destroyed when it goes out of scope.
99: m_pnData = pnData;
100: m_nLength = nNewLength;
101: }
102:
103: void InsertBefore(int nValue, int nIndex)
104: {
105: // Sanity check our nIndex value
106: assert(nIndex >= 0 && nIndex <= m_nLength);
107:
108: &nb
补充:软件开发 , C++ ,