提问者:小点点

从控制台删除最后打印的元素


问题给定两个大小为N的未排序数组A和大小为M的元素不同的数组B,任务是从这两个数组中找出所有和等于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,

我的代码

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

我已经试过了/B/B,但是在这里不起作用,我不知道为什么,请帮我打印正确的输出,并建议我一个更好的方法

我得把打印的最后一个逗号去掉。


共2个答案

匿名用户

替换以下内容:

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

与:

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

侧注:不要包括

匿名用户

bool first = true;
for (auto x : mp)
{
    if (!first)
    {
        cout << ", ";
    }
    cout << x.first << " " << x.second;
    first = false;
}