【发布时间】: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”来测试程序。 lm 和 lp 的大小都是 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
mergefunction?