0

suppose my file contains Names

         Nitish
         Prudhvi Raj Borra  
         Rajesh
         Srinath

now what the questions i want to update the file i mean i want to append some data in the file suppose i want to enter The Name "Sarath Chandra"

the file should updated in sorted order like this

         Nitish
         Prudhvi Raj Borra  
         Rajesh
         Sarath Chandra
         Srinath

so my method in at first i will store all the words in an vector

                     string line;
                    ifstream fin("somefile.txt");
                    while(!fin.eof()){
    fin>>line;//fin 
            v.push_back(line);//v some be vector name
}

i will also the entered name in vector and sort like this

                 sort(v.begin,v.end);

and after wards i will open the file in write mode and then copy back the vector contents into the file but this takes so much memory is there any method to update a file without using any extra memory

Rajesh M
  • 634
  • 11
  • 31

1 Answers1

0

Per http://www.cplusplus.com/reference/algorithm/sort/, vector::sort performs at O(nlogn) time, though it doesn't have any information about overhead. If you would really like to save memory, you could write a function that sorts the data in place, or try to take advantage of inplace_merge (http://www.cplusplus.com/reference/algorithm/inplace_merge/). I have never used that particular function though, so I don't know whether it's exactly what you are looking for or not.

This also might be useful to you: How to sort in-place using the merge sort algorithm?

A naive solution would be to use a bubble sort, which is in place, but if you have so much data that you are worried about memory then this will be a very slow solution.

One more thing: if you know the file is already sorted, it takes no overhead (beyond storing the name to be inserted) and O(n) insertion time to simply parse the file until you find the correct insertion point.

Community
  • 1
  • 1
IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17