簡體   English   中英

如果值等於鍵,則合並映射中的條目

[英]Merge entries in map if value equals key

我有一個帶有以下值的std :: map:

2 31
4 36
5 29
6 24
24 49
25 83
29 63
36 42
42 79

現在,如果值存在鍵,我想“合並”值。 所以期望的輸出(數據結構無關)將是:

2 31
4 36 42 79
5 29 63
6 24 49
25 83

我已經嘗試迭代遍歷地圖並對每個值使用std :: find。 但我遇到的矢量大小超過3的問題,對於大型地圖來說似乎非常慢。 這是一個小例子,沒有給出所需的輸出:

int main(int argc, char** argv)
{   
    std::map<int, int> my_map = { {2, 31}, {4, 36}, {5, 29}, {6, 24}, {24, 49}, {25, 83}, {29, 63}, {36, 42}, {42, 79} };

    std::vector<int> temp_vec;
    std::vector<std::vector<int>> destination_vec;

    for (auto it = my_map.begin(); it != my_map.end(); ++it) {

        std::map<int, int>::iterator map_iterator = my_map.find(it->second);
        if (map_iterator == my_map.end()) {
            temp_vec.push_back(it->first);
            temp_vec.push_back(it->second);
        }
        else {
            temp_vec.push_back(it->first);
            temp_vec.push_back(it->second);
            temp_vec.push_back(map_iterator->second);
            // I stopped here because I could try another if loop here or a while loop for the whole process but it seems very inefficient
        }
        destination_vec.push_back(temp_vec);
        temp_vec.clear();
    }
}   

假設您的地圖無法鏈接較小的值( {{1, 42},{2, 1}} )。

您可以使用:

std::map<int, std::vector<int>> foo(std::map<int, int> m)
{
    std::map<int, std::vector<int>> res;

    while (!m.empty())
    {
        auto it = m.begin();
        const auto key = it->first;
        auto& v = res[key];

        while (it != m.end()) {
            auto value = it->second;
            v.push_back(value);
            m.erase(it);
            it = m.find(value);
        }
    }
    return res;
}

演示

復雜度是O(n log n)

暫無
暫無

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

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