最近和师兄的课题交流,特别是这两天重点集中到实践上。动态分配存储空间和输入输出文件无疑是非常重要的。
这里仍记录以下今天借阅的这本C++给出的一些例子:
动态内存的模拟
struct memo{ int start; int finish; memo* next; }; void arrange(memo* memo) { memo* insPos = head, *curPos, *minPos; while(insPos->next != NULL){ //直接插入排序 curPos = minPos = insPos; while(curPos->next = NULL){ //找起始地址最小的结点 if(curPos->next->start<minPos->next->start) minPos = curPos; curPos = curPos -> next; } //插入最小节点 curPos = minPos -> next; minPos -> next = curPos -> next; curPos -> next = insPos -> next; insPos -> next = curPos; intPos = insPos -> next; } //合并连续的内存块 for(curPos = head -> next; curPos -> next !=NULL; curPos = curPos -> next){ //当前块与下一块连续,执行合并 while(curPos->finish + 1 == curPos->next->start){ minPos=curPos->next; curPos->finish=minPos->finish; curPos->next=minPos->next; delete minPos; if(curPos->next==NULL)return; } }
另外一个非常实用的程序:统计一个文件中单词使用的频率
#include <iostream> #include <iomanip> #include <fstream> using namespace std; struct word{ char data[20]; int count; }; void getWord(ifstream &fp, char ch[]); //从文件中读入一单词 void doubleSpace(word* &list, int &size); //扩大数组空间 int main() { ifstream in("txt.txt"); char ch[20]; int size = 10, len = 0, i, j; word* result = new word[10]; if(!in){cout <<"文件打开错误"<<endl;return 1;} while(true){ //读文件直到结束 getWord(in, ch); //读入一个单词ch if(ch[0]=='