Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::mutiset vs std::vector to read and write sorted strings to a file

Tags:

c++

stl

I've a file say somefile.txt it contains names (single word) in sorted order.

I want to updated this file, after adding new name, in sorted order.

Which of the following will be most preferred way and why ?

Using a std::multiset

std::multiset<std::string> s;

std::copy(std::istream_iterator<std::string>(fin),//fin- object of std::fstream
          std::istream_iterator<std::string>(), 
          std::inserter(s, s.begin())); 

s.insert("new_name");

//Write s to the file

OR

Using a std::vector

std::vector<std::string> v;

std::copy(std::istream_iterator<std::string>(fin),
              std::istream_iterator<std::string>(), 
              std::back_inserter(v));

v.push_back("new_name");

std::sort(v.begin(),v.end());

//Write v to the file.
like image 440
P0W Avatar asked Sep 01 '25 05:09

P0W


1 Answers

The multiset is slower to insert objects than the vector, but they are held sorted. The multiset is likely to take up more memory than the vector as it has to hold pointers to an internal tree structure. This may not always be the case as the vector may have some empty space.

I guess if you need the information to grow incrementally but always to be ready for immediate access in order then the multi set wins.

If you collect the data all at once without needing to access it in order, it is probably simpler to push it onto the vector and then sort. So how dynamic is the data to be stored is the real criterion.

like image 106
David Elliman Avatar answered Sep 02 '25 19:09

David Elliman