自由,民主,平等,博爱,进步.
中华民国,我的祖国,中华民国万岁!中华民国加油!
本人自愿加入中国国民党,为人的自由性,独立性和平等性而奋斗!
// 请注意,这里插入的位置相对于 0 位置而言,也就是说,如果你要求的插入位置为3,他将插入在原数组的第四个元素之前。
#include <iostream> #include <cstdlib> #include <memory.h> using namespace std;
class Demo { private: int * your_integer_array; int size_of_your_integer_array; public: Demo(); bool creat_your_integer_array(const int const * an_integer_array, int size); void insert_element_at_a_position(int pos, const int element); void display() { if(your_integer_array) { for(int i = 0; i<size_of_your_integer_array; i++) { cout<<your_integer_array[i]<<" "; } } } ~Demo() { if(your_integer_array && size_of_your_integer_array == 1) delete your_integer_array; else if(your_integer_array) delete [] your_integer_array; else ; } };
Dem:Demo() { your_integer_array = NULL; size_of_your_integer_array = 0; } bool Dem:creat_your_integer_array(const int const * an_integer_array, int size) { bool success = false; if(size && an_integer_array) { if(your_integer_array && size_of_your_integer_array==1) { delete your_integer_array; your_integer_array = new int[size]; if(your_integer_array) { success = true; size_of_your_integer_array = size; memcpy(your_integer_array, an_integer_array, size*sizeof(int)); } } else if(your_integer_array) { delete [] your_integer_array; your_integer_array = new int[size]; if(your_integer_array) { success = true; size_of_your_integer_array = size; memcpy(your_integer_array, an_integer_array, size*sizeof(int)); } } else { your_integer_array = new int[size]; if(your_integer_array) { success = true; size_of_your_integer_array = size; memcpy(your_integer_array, an_integer_array, size*sizeof(int)); } } } return success; } void Dem:insert_element_at_a_position(int pos, const int element) { int * temp = NULL; if(your_integer_array && pos<size_of_your_integer_array) { temp = new int[size_of_your_integer_array+1]; memcpy(temp, your_integer_array, pos*sizeof(int)); temp[pos] = element; memcpy(&temp[pos+1], &your_integer_array[pos], (size_of_your_integer_array-pos)*sizeof(int)); if(size_of_your_integer_array>1) { delete [] your_integer_array; size_of_your_integer_array++; your_integer_array = new int[size_of_your_integer_array]; memcpy(your_integer_array, temp, size_of_your_integer_array*sizeof(int)); delete [] temp; } else { delete your_integer_array; size_of_your_integer_array++; your_integer_array = new int[size_of_your_integer_array]; memcpy(your_integer_array, temp, size_of_your_integer_array*sizeof(int)); delete [] temp; } } }
int main() { int test_array[10] = {1,2,3,4,5,6,7,8,9,10}; int size = sizeof(test_array)/sizeof(int); int element = 108; int pos = 3; Demo myDemo; myDemo.creat_your_integer_array(test_array, size); myDemo.insert_element_at_a_position(pos, element); myDemo.display(); cout<<endl; system("pause"); return 0; }