采取以下步骤,沿着每条线向下,箭头代表移动。例如,在第一步之后,0 已从 A 中删除,而 final 只有一个项目:
列表:A 最终 B
0 --> 0
4 1
5 2
6 3
std::list 示例:
std::list<int> A, B;
A.push_back(0); A.push_back(1); A.push_back(2); A.push_back(3);
B.push_back(4); A.push_back(5); A.push_back(6);
std::list<int> final;
for (std::list<int>::iterator a, b;
(a = A.begin()) != A.end() and (b = B.begin()) != B.end();)
{
final.splice(final.end(), A, a);
final.splice(final.end(), B, b);
}
for (std::list<int>::iterator x; (x = A.begin()) != A.end();) {
final.splice(final.end(), A, x);
}
for (std::list<int>::iterator x; (x = B.begin()) != B.end();) {
final.splice(final.end(), B, x);
}
提取拼接会稍微清理一下,但更重要的是,您应该能够为您的(显然是自定义的)列表类型编写以下 move_back,然后使用它与 std::list 相同:
// Moves pos from source into dest; returns what was the position after
// pos in the source list.
template<class List>
typename List::iterator move_back(List &dest, List &source,
typename List::iterator pos)
{
typename List::iterator next = pos;
++next;
dest.splice(dest.end(), source, pos);
return next;
}
template<class List>
void move_back(List &dest, List &source) {
dest.splice(dest.end(), source, source.begin(), source.end());
}
void example() {
std::list<int> A, B;
A.push_back(0); A.push_back(1); A.push_back(2); A.push_back(3);
B.push_back(4); A.push_back(5); A.push_back(6);
std::list<int> final;
for (std::list<int>::iterator a = A.begin(), b = B.end();
a != A.end() and b != B.end();)
{
a = move_back(final, A, a);
b = move_back(final, B, b);
}
move_back(final, A);
move_back(final, B);
}