109: int *pnData = new int[m_nLength+1];
110:
111: // Copy all of the elements up to the index
112: for (int nBefore=0; nBefore < nIndex; nBefore++)
113: pnData[nBefore] = m_pnData[nBefore];
114:
115: // insert our new element into the new array
116: pnData[nIndex] = nValue;
117:
118: // Copy all of the values after the inserted element
119: for (int nAfter=nIndex; nAfter < m_nLength; nAfter++)
120: pnData[nAfter+1] = m_pnData[nAfter];
121:
122: // Finally, delete the old array, and use the new array instead
123: delete[] m_pnData;
124: m_pnData = pnData;
125: m_nLength += 1;
126: }
127:
128: void Remove(int nIndex)
129: {
130: // Sanity check our nIndex value
131: assert(nIndex >= 0 && nIndex < m_nLength);
132:
133: // First create a new array one element smaller than the old array
134: int *pnData = new int[m_nLength-1];
135:
136: // Copy all of the elements up to the index
137: for (int nBefore=0; nBefore < nIndex; nBefore++)
138: pnData[nBefore] = m_pnData[nBefore];
139:
140: // Copy all of the values after the inserted element
141: for (int nAfter=nIndex+1; nAfter < m_nLength; nAfter++)
142: pnData[nAfter-1] = m_pnData[nAfter];
143:
144: // Finally, delete the old array, and use the new array instead
145: delete[] m_pnData;
146: m_pnData = pnData;
147: m_nLength -= 1;
148: }
149:
150: // A couple of additional functions just for convenience
151: void InsertAtBeginning(int nValue) { InsertBefore(nValue, 0); }
152: void InsertAtEnd(int nValue) { InsertBefore(nValue, m_nLength); }
153:
154: int GetLength() { return m_nLength; }
155: };
156:
157: #endif
158:
159: Now, let’s test it just to prove it works:
160: 1
161: 2
162: 3
163: 4
164: 5
165: 6
166: 7
167: 8
168: 9
169: 10
171: 12
172: 13
173: 14
174: 15
175: 16
176: 17
177: 18
178: 19
179: 20
180: 21
181: 22
182: 23
183: 24
184: 25
185: 26
186: 27
187: 28
188: 29
189: 30www.2cto.com
190: 31
191: 32
192: 33
193:
194: #include
195: #include "IntArray.h"
196:
197: using namespace std;
198:
199: int main()
200: {
201: // Declare an array with 10 elements
202: IntArray cArray(10);
203:
204: // Fill the array with numbers 1 through 10
205: for (int i=0; i<10; i++)
206: cArray[i] = i+1;
207:
208: // Resize the array to 8 elements
209: cArray.Resize(8);
210:
211: // Insert the number 20 before the 5th element
212: cArray.InsertBefore(20, 5);
213:
214: // Remove the 3rd element
215: cArray.Remove(3);
216:
217: // Add 30 and 40 to the end and beginning
218: cArray.InsertAtEnd(30);
219: cArray.InsertAtBeginning(40);
220:
221: // Print out all the numbers
222: for (int j=0; j
224:
225: return 0;
226: }
钟谢伟