简体   繁体   English

如果值等于键,则合并映射中的条目

[英]Merge entries in map if value equals key

I have a std::map with the following values: 我有一个带有以下值的std :: map:

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

Now I want to "merge" values if a key exists for a value. 现在,如果值存在键,我想“合并”值。 So the desired output (data structure is irrelevant) would be: 所以期望的输出(数据结构无关)将是:

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

I have tried iterating through the map and using std::find for every value. 我已经尝试迭代遍历地图并对每个值使用std :: find。 But I am having problems with vector sizes greater than 3 and it seems to be very slow for large maps. 但我遇到的矢量大小超过3的问题,对于大型地图来说似乎非常慢。 Here is a small example not giving exactly the desired output: 这是一个小例子,没有给出所需的输出:

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();
    }
}   

Assuming your map cannot link smaller values (as {{1, 42},{2, 1}} ). 假设您的地图无法链接较小的值( {{1, 42},{2, 1}} )。

You might use: 您可以使用:

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

Demo 演示

complexity is O(n log n) . 复杂度是O(n log n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM