【问题标题】:std::mutiset vs std::vector to read and write sorted strings to a filestd::mutiset vs std::vector 读取和写入排序字符串到文件
【发布时间】: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.

【问题讨论】:

  • 注意:您应该使用范围构造函数而不是复制。 (虽然考虑到这些只是输入迭代器,但差异会很小)

标签: c++ stl


【解决方案1】:

多重集插入对象比向量慢,但它们保持排序。 多重集可能比向量占用更多的内存,因为它必须保存指向内部树结构的指针。这可能并非总是如此,因为向量可能有一些空白空间。

我猜如果您需要信息以增量方式增长,但始终准备好立即访问以便多集获胜。

如果您一次收集所有数据而不需要按顺序访问它,则将其推送到向量上然后排序可能更简单。所以要存储的数据有多动态才是真正的标准。

【讨论】:

    【解决方案2】:
    std::string new_name = "new_name";
    bool inserted = false;
    std::string current;
    while (std::cin >> current) {
        if (!inserted && new_name < current) {
            std::cout << new_name << '\n';
            inserted = true;
        }
        std::cout << current << '\n';
    }
    

    【讨论】:

      【解决方案3】:

      这两个选项基本上是等价的。

      在性能关键的情况下,vector 方法会更快,但在这种情况下,您的性​​能在很大程度上会受到磁盘的限制;您选择哪个容器并不重要。

      【讨论】:

      • 是的。据说 set 容器的插入和移除速度更快,但最后除外,但我听说也并非总是如此。我认为是主人自己的。这与向量在内存中的紧凑性有关。
      【解决方案4】:

      从这家伙的测试 (http://fallabs.com/blog/promenade.cgi?id=34) 中我可以看出,向量的速度更快。我建议你测试一下,自己看看。性能通常与平台有关,尤其是在这种情况下,与数据集有关。

      从他的测试中,他得出结论,简单元素最适合矢量。对于复杂元素(例如超过 4 个字符串),multiset 更快。

      此外,由于向量是大数组,如果您要添加大量数据,可能值得考虑使用另一种类型的容器(例如链表或专门的 boost 容器,请参阅Is there a sorted_vector class, which supports insert() etc.?)。

      【讨论】:

        猜你喜欢
        • 2012-09-04
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        相关资源
        最近更新 更多