c++ - updating a file in sorted order -
suppose file contains names
nitish prudhvi raj borra rajesh srinath now questions want update file mean want append data in file suppose want enter name "sarath chandra"
the file should updated in sorted order this
nitish prudhvi raj borra rajesh sarath chandra srinath so method in @ first store words in vector
string line; ifstream fin("somefile.txt"); while(!fin.eof()){ fin>>line;//fin v.push_back(line);//v vector name } i entered name in vector , sort this
sort(v.begin,v.end); and after wards open file in write mode , copy vector contents file takes memory there method update file without using memory
per http://www.cplusplus.com/reference/algorithm/sort/, vector::sort performs @ o(nlogn) time, though doesn't have information overhead. if save memory, write function sorts data in place, or try take advantage of inplace_merge (http://www.cplusplus.com/reference/algorithm/inplace_merge/). have never used particular function though, don't know whether it's looking or not.
this might useful you: how sort in-place using merge sort algorithm?
a naive solution use bubble sort, in place, if have data worried memory slow solution.
one more thing: if know file sorted, takes no overhead (beyond storing name inserted) , o(n) insertion time parse file until find correct insertion point.
Comments
Post a Comment