【问题标题】:merged list doesn't show in the terminal合并列表未显示在终端中
【发布时间】:2021-11-15 04:55:03
【问题描述】:
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
using namespace std;

void out(string& str) {cout << str << " ";}

int main()
{
    list<string> lm;
    list<string> lp;
    string temp;
    cout << "List of Mat (quit to quit):\n";
    while (cin >> temp && temp != "quit")
        lm.push_back(temp);
    lm.sort();
    for_each(lm.begin(), lm.end(), out);
    cout << endl;
    cout << "Mat completed.\n";
    cout << "List of Pat (quit to quit):\n";
    while (cin >> temp && temp != "quit")
        lp.push_back(temp);
    for_each(lp.begin(), lp.end(), out);
    cout << endl;

    list<string> merged;
    merge(lm.begin(), lm.end(), lp.begin(), lp.end(), merged.begin());
    cout << "Merged list (sorted):\n";
    merged.sort();
    merged.unique();
    for_each(merged.begin(), merged.end(), out);
    cout << endl;

    return 0;
}

我通过为lm 输入“a t g c”和为lp 输入“u a k g”来测试程序。 lmlp 的大小都是 4。

但是在merge(lm.begin(), lm.end(), lp.begin(), lp.end(), merged.begin());之后,merge的大小似乎是无限的,并且合并后无法在终端中显示。

我想知道我使用merge 是否有问题,或者还有其他问题。谢谢!!!

【问题讨论】:

  • 旁注:merge 需要两个 sorted 集合。我不认为lp 保证在这里排序;你错过了给sort的电话
  • 请注意,std::merge "[m] 将两个排序范围 [first1, last1) 和 [first2, last2) 合并为一个排序 范围从 d_first 开始。" (特别强调我的)。你不需要merged.sort()
  • 关于@AndyG 提到的主题:您可以将输入+排序业务包装在一个只需调用两次的函数中。
  • 为什么不使用the lists own merge function

标签: c++ stl


【解决方案1】:

在这些线上

list<string> merged;
merge(lm.begin(), lm.end(), lp.begin(), lp.end(), merged.begin());

要将成员复制到merged,您需要使用插入器

list<string> merged;
merge(lm.begin(), lm.end(), lp.begin(), lp.end(), std::back_inserter(merged));

【讨论】:

  • 请问为什么我在merge() 中需要一个std::back_inserter ?看来merged.begin()也可以是Output Iterator。
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2017-08-31
相关资源
最近更新 更多