簡體   English   中英

如何(有效地)將地圖作為值插入到地圖中?

[英]How to (efficiently) insert into a map with a map as value?

我正在編寫一個C ++程序,逐行讀取大文件,並將每個line-info(經過一些處理后)插入到unordered_map中。

這是unordered_map的聲明:

unordered_map<int, unordered_map<int, int> > entries;

我做的插入是(這是在循環代碼塊中,我處理文本文件的每一行):

unordered_map<int, int> tmp;
tmp[y] = z;
entries[x] = tmp;

但事實證明,這在性能方面表現不佳。

我已經嘗試創建一pair<int, pair<int, int>>並使用entries.insert(the_pair)插入它但是我無法將其編譯(獲取: no matching member function for call to 'insert' )。

編輯:
該程序如下所示:

ifstream ifile(path-to-file);
string line;
unordered_map<int, unordered_map<int, int> > entries;
while (getline(ifile, line)) {
    // some processing with line to find (int) x and (int) y 
    if (entries.find(x) == entries.end()) {
        auto iter_and_success = entries.emplace(x, unordered_map<int, int>{});
        auto &tmp_m = iter_and_success.first->second;
        tmp_m[y] = 1;
    }
    else {
        unordered_map<int, int> r = entries[x];
        if (r.count(y) == 0)
            entries[x][y] = (int) r.size() + 1;
    }
}

我認為最好的辦法就是將子unordered_map移動到父級:

entries[x] = std::move(tmp);

這樣你就可以避免使用額外的tmp副本。

另一種方法是插入填充子地圖。

 auto iter_and_success = entries.emplace(x, unordered_map<int, int>{});
 auto& tmp = iter_and_success.first->second;
 tmp[y] = z;

實際上,如果x恰好多次出現(如果這是不需要的行為 - 只需檢查bool標志並采取相應的行為),您就會將數據附加到子映射。


ifstream ifile(path-to-file);
string line;
unordered_map<int, unordered_map<int, int> > entries;
while (getline(ifile, line)) {
    // some processing with line to find (int) x and (int) y 

    // This will insert a new map only if x wasn't present
    auto iter_and_success = entries.emplace(x, unordered_map<int, int>{});

    // This will be 1 if a new map was inserted
    auto value_to_insert = static_cast<int>(iter_and_success.first->second.size()) + 1;

    // This will do anything only if y wasn't present in sub-map
    iter_and_success.first->second.emplace(y, value_to_insert);
}

暫無
暫無

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

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