How to extract pairs from a collection of vectors?

Hi all!
I am stuck with the following problem. I have a map m from int to vector<int>, i.e. suppose we have map<int, vector<int> > m.

I want to write a function that constructs all the possible pairs from consecutive vectors of the value of this map. To explain more clearly, suppose the map m is the following:

1
2
3
4
5
6
7
  {  
    1: [0],  
    3: [3, 4],  
    4: [1, 5, 7],  
    5: [5],  
    7: [2]  
}  


I would like to construct the following pairs: {(0,3); (0,4); (3,1); (3,5); (3,7); (4,1);
(4,5); (4,7); (1,5); (5,5); (7,5); (5,2)}.

[By the way, my real goal is to find the maximum value (in absolute value)
between the differences of such pairs, i.e max(3-0, 4-0, 3-1, ... etc.)]

How should that possibly be done? Thank you a lot for your help!
Last edited on
Not a very elegant solution, but it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <map>
#include <utility>
#include <vector>

int main()
{
    std::map<int, std::vector<int>> m{
        { 1, { 0 } }, { 3, { 3, 4 } },
        { 4, { 1, 5, 7 } }, { 5, { 5 } },
        { 7, { 2 } },
    };
    
    std::vector<std::pair<int, int>> pairs{};
    for( auto i = m.begin(); i != m.end(); i++ ) {
        for( int n : i->second ) {
            auto temp = i; temp++;
            if( temp == m.end() ) break;
            for( int o : temp->second )
                pairs.push_back( { n, o } );
        }
    }
    
    for( const auto& p : pairs )
        std::cout << '(' << p.first << ", " << p.second << ")\n";
}


(0, 3)
(0, 4)
(3, 1)
(3, 5)
(3, 7)
(4, 1)
(4, 5)
(4, 7)
(1, 5)
(5, 5)
(7, 5)
(5, 2)
Thank you for your code, I find it nice. I have only one question: since I am new to C++ and don't yet have studied C++11 could you please rewrite the program only with C++ commands (ie without auto, etc?) thanks a lot!

I have only one question: since I am new to C++ and don't yet have studied C++11 could you please rewrite the program only with C++ commands (ie without auto, etc?

Being new to C++ shouldn't prevent you from using the newer C++ features. These features are designed to make your life much easier and should be used as much as possible. For example, would you prefer to write this
for( std::map<int, std::vector<int>>::iterator i = m.begin(); i != m.end(); i++ )
or this
for( auto i = m.begin(); i != m.end(); i++ )
It should be evident which method sane programmers would prefer.

I won't replace the auto and range-based for loops with pre-C++11 code as that would be counter-intuitive. If you have an up to date compiler, why not take advantage of the features C++ has to offer?

Anyway, if there's something you're unsure about go ahead and ask and I'll try to answer it to the best of my ability. Hope this helps.
Topic archived. No new replies allowed.