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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With