【问题标题】:Delete last printed element from console从控制台删除最后打印的元素
【发布时间】:2020-07-13 12:05:00
【问题描述】:

问题给定两个大小为 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 但它在这里不起作用我不知道为什么请帮我打印正确的输出并建议我一个更好的方法

我必须删除最后打印的逗号。

【问题讨论】:

  • 因此您可以将问题简化为:如何避免在以下循环中打印最后一个逗号? for (auto x : mp) { cout &lt;&lt; x.first &lt;&lt; " " &lt;&lt; x.second &lt;&lt; ","; }

标签: c++ c++11 c++14


【解决方案1】:
bool first = true;
for (auto x : mp)
{
    if (!first)
    {
        cout << ", ";
    }
    cout << x.first << " " << x.second;
    first = false;
}

【讨论】:

    【解决方案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
            }
        }
    

    旁注: Don't include &lt;bits/stdc++&gt;

    【讨论】:

    • 谢谢。但是 是怎么回事,你能告诉我那有什么问题吗
    • 阅读我输入的链接,它解释得很好。但简单地说,只需包含您需要的标题,即:&lt;map&gt;, &lt;iostream&gt;
    猜你喜欢
    • 2023-02-07
    • 2021-01-17
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2021-10-18
    • 2012-08-18
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多