1

QUESTION Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.

 **INPUT**
    1
    5 5 9
    1 2 4 5 7
    5 6 3 4 8


**EXPECTED OUTPUT** 1 8, 4 5, 5 4

**MY OUTPUT**   1 8, 4 5, 5 4,

MY CODE

#include<bits/stdc++.h>
using namespace std;
void Pair(int *a, int*b, int n, int m, int sum) {
    map<int, int>mp;
    for (int i = 0; i < n; i++) {
        int x = a[i];
        for (int i = 0; i < m; i++) {
            if ((sum - x) == b[i])
                mp[x] = b[i];
        }
    }

    for (auto x : mp) {
        cout << x.first << " " << x.second << ",";
         
    }
  
}
int main() {

    int  test ;
    cin >> test;
    for (int i = 0; i < test; i++) {
        int  a[1000000];
        int  b[1000000];
        int  n, m, sum;
        cin >> n >> m >> sum;
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        for (int i = 0; i < m; i++) {
            cin >> b[i];
        }
        Pair(a, b, n, m, sum); 
       
        cout << endl;
    }
    return 0;
}

I have already tried /b/b but it does not works here I don't know why please help me print the correct output and also suggest me a better way of doing it

I have to remove the last comma printed.

Waqar
  • 6,944
  • 2
  • 26
  • 39
aviral
  • 15
  • 5
  • So you could reduce your question to: how can I avoid printing the last comma in the following loop? `for (auto x : mp) { cout << x.first << " " << x.second << ","; }` – rturrado Jul 13 '20 at 12:46

2 Answers2

2
bool first = true;
for (auto x : mp)
{
    if (!first)
    {
        cout << ", ";
    }
    cout << x.first << " " << x.second;
    first = false;
}
rturrado
  • 4,139
  • 4
  • 35
  • 51
1

Replace this:

    for (auto x : mp) {
        cout << x.first << " " << x.second << ",";
         
    }

with:

    auto it = mp.begin();
    auto end = mp.end();
    for (; it != end; ++it) {
        cout << (*it).first << ' ' << (*it).second;
        if ( std::next(it, 1) != end) { // check if next is end
            cout << ", "; //if not, print a comma
        }
    }

Side note: Don't include <bits/stdc++>

Waqar
  • 6,944
  • 2
  • 26
  • 39