簡體   English   中英

std :: mutiset vs std :: vector用於讀取和寫入已排序的字符串到文件

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

我有一個文件說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.

多重插入對象的插入速度比向量慢,但它們保持排序。 多集合可能占用比向量更多的內存,因為它必須保存指向內部樹結構的指針。 這可能並非總是如此,因為向量可能具有一些空白空間。

我想如果您需要增量增長的信息,但總是准備立即訪問,那么多組獲勝。

如果您一次性收集數據而無需按順序訪問它,則將其推送到向量然后排序可能更簡單。 因此,存儲數據的動態性是真正的標准。

兩種選擇基本相同。

在性能關鍵的情況下, vector方法會更快,但在這種情況下,你的性能很大程度上受到磁盤的限制; 你選擇哪個容器並不重要。

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';
}

從這個人的測試中可以看到的向量更快( http://fallabs.com/blog/promenade.cgi?id=34 )。 我建議你測試一下,看看你自己。 性能通常與平台有關,尤其是在這種情況下,數據集。

從他的測試中,他得出結論,簡單元素最適合矢量。 對於復雜元素(例如,超過4個字符串),multiset更快。

此外,由於向量是大數組,如果你要添加大量數據,可能值得研究使用其他類型的容器(例如鏈接列表或專用的boost容器,請參閱是否有sorted_vector類,它支持insert()等等? )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM