我的使用技巧
std::merge
可能失败。我没有足够的创造力去理解为什么有人会写
merge
所以它可以,但它违反了
Compare
正如下面的评论所指出的,所以有人可以。
无论如何,
合并
是一种过度杀伤力的解决方案。隐藏额外工作的代码行更少,因为
合并
它的用途比我们这里要复杂得多。
例子:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>
template<typename IN1,
typename IN2,
typename OUT>
inline OUT interleave(IN1 it1,
IN1 end1,
IN2 it2,
IN2 end2,
OUT out)
{
// interleave until at least one container is done
while (it1 != end1 && it2 != end2)
{
// insert from container 1
*out = *it1;
out++;
it1++;
// insert from container 2
*out = *it2;
out++;
it2++;
}
if (it1 != end1) // check and finish container 1
{
return std::copy (it1, end1, out);
}
else if (it2 != end2)// check and finish container 2
{
return std::copy (it2, end2, out);
}
return out; // both done
}
int main()
{
// fill the containers with numbers
std::vector<int> in1 = {1,3,5,7,9};
std::list<int> in2 = {8,6,4,2};
// construct output container of sufficient size.
// Could also use empty container and *_inserter
std::deque<int> out(in1.size() + in2.size());
// Container-agnostic. reads from vector and list and stores in deque
interleave(in1.begin(), in1.end(),
in2.begin(), in2.end(),
out.begin());
for (int val: out)
{
std::cout << val << ' ';
}
}
注意:而不是通过交换输入顺序和使所有用户
interleave
为此付费,调用方应按输入参数的顺序进行调用。