【发布时间】:2013-08-08 20:21:06
【问题描述】:
我有一个文件说 somefile.txt 它包含按排序顺序排列的名称(单个单词)。
我想在添加新名称后按排序顺序更新此文件。
以下哪种方式最受青睐?为什么?
使用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
或
使用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.
【问题讨论】:
-
注意:您应该使用范围构造函数而不是复制。 (虽然考虑到这些只是输入迭代器,但差异会很小)