/** */ /** * C++ 中动态的插入、删除数据. * * 雲飛揚 * 2008.4.14 */ #include < iostream > using namespace std; /**/ /*///*/ const int maxSize = 1024 ; const int listMax = 20 ; /**/ /*///*/ class DateOperation // 声明类 ... {public: typedef struct ...{ public: int data[maxSize]; int length; }dateBase; bool insert(dateBase *value, int member, int locat); bool del(dateBase *value, int locat); dateBase *createList(); void input(dateBase value);} ; /**/ /*///*/ bool DateOperation::insert(dateBase * value, int member, int locat) ... { if(value->length == maxSize - 1) ...{ return false; } if ((locat < 1) || (locat > value->length + 1)) ...{ return false; } int tmp = value->data[locat - 1]; for(int j = value->length - 1;j >= locat;--j) ...{ value->data[j + 1] = value->data[j]; } value->data[locat] = tmp; value->data[locat - 1] = member; value->length = value->length + 1; return true;} bool DateOperation::del(dateBase * value, int locat) ... { if ((locat < 1) || (locat > value->length)) ...{ return false; } else ...{ for(int j = locat;j <= value->length - 1;++j) ...{ value->data[j - 1] = value->data[j]; } value->length--; } return true;} DateOperation::dateBase * DateOperation::createList() ... { int n,locat; dateBase *value = new dateBase; cout <<"请输入元素个数:" << endl; cin.clear(); cin >> n; if(n <= 0 || n > listMax) ...{ cout << "ERROR, 输入的元素个数不正确, 请在 1 - " << listMax << " 之间. "; createList(); } for(locat = 0;locat < n;++locat) ...{ cout << "data[" << locat + 1<< "]=" << endl; cin >> (value->data[locat]); } value->length = n; cout << " "; return value;} void DateOperation::input(dateBase value) ... { for(int index = 0;index != value.length;++index) ...{ cout << "data[" << index + 1 << "] = " << value.data[index] << endl; }} /**/ /*///*/ int main( void ) ... { DateOperation Operation; DateOperation::dateBase *value; int s = -1; int locat, member; value = Operation.createList(); Operation.input(*value); while(0 != s) ...{ cout << "1......插入元素 2......删除元素 0......退出 "; cin.clear(); cin >> s; if(s < 0 || s > 2) ...{ cout << "ERROR, 输入的选项不正确! "; continue; } switch (s) ...{ case 1: cout << "请输入插入的元素: "; member = -1; cin.clear(); cin >> member; if(member < 0) ...{ cout << "ERROR, 输入的元素不合法! "; continue; } cout << "请输入插入位置: "; locat = -1; cin >> locat; if(locat < 0) ...{ cout << "ERROR, 输入的位置不合法! "; continue; } if(false == Operation.insert(value, member, locat)) ...{ cout << "插入元素失败! "; continue; } Operation.input(*value); break; case 2: cout << "请输入删除元素的位置: "; locat = -1; cin.clear(); cin >> locat; if(locat < 0) ...{ cout << "ERROR, 输入的删除位置不合法! "; continue; } if(false == Operation.del(value, locat)) ...{ cout << "删除元素失败! "; continue; } Operation.input(*value); break; default: ; } } delete value; return 0;}