Мой шаг использования std::merge
может закончиться неудачей. Я не достаточно изобретателен, чтобы понять, почему кто-то может написать merge
, чтобы это могло, но это нарушает требования для Сравните , как указано в комментариях ниже, чтобы кто-то мог.
Независимо от того, merge
- это решение для перерасхода. Это меньше строк кода, скрывающих дополнительные усилия, потому что предполагаемое использование merge
для более сложной работы, чем мы делаем здесь.
Пример:
#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
платить за это, вызывающий должен вызывать с обратным порядком ввода параметров.