Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating unordered map in C++ for counting the pairs

So let’s say I have an array, 1 2 1 2 3 4 2 1 and I want to store all the (arr[i], arr[i-1)
such that arr[i] != arr[i-1] as a pair in unordered_map for counting these pairs.

For e.g.

(1, 2)  -> 2
(2, 3) -> 1
(3, 4) -> 1
(4, 2) -> 1
(2, 1) -> 1

So the syntax I tried,

unordered_map<pair<int, int>,  int> umap;
        int temp; 
        cin>>temp;
        arr[i]=temp;
        for (int i=1; i< n; i++){
            cin>>temp;
            arr[i]=temp;
            
            umap[(arr[i-1], arr[i])]++;
            
        }
        
    }

Next thing, I also tried with proper definition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

unordered_map<pair<int, int>,  int> umap;
        cin>>temp;
        arr[i]=temp;
        for (int i=1; i< n; i++){
            cin>>temp;
            arr[i]=temp;
            pair<int, int> p(arr[i-1], arr[i]);
            umap[p]++;
            
        }
        
    }

Can anybody please help me getting the right syntax? Thanks in advance

>Solution :

You can’t just use unordered_map with a pair because there is no default hash implemented.
You can however use map which should work fine for your purpose because pair does implement <.
See Why can't I compile an unordered_map with a pair as key? when you really want unordered_map.

You can construct pair with curly braces like this

umap[{arr[i-1], arr[i]}]++;

I think from C++11 onward, but it might be C++14 or even C++17

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading