我想拼接 range [first, last]
,包括两个端点。我对元素before first
和 to有迭代器last
。我可以做到这一点,splice_after()
但只能在线性时间内。
我相信这个拼接可以在恒定时间内完成。我该怎么做std::forward_list
?
如果问题不清楚,这里是显示我的问题的示例代码:
实时工作空间代码
#include <algorithm>
#include <forward_list>
#include <iostream>
#include <iterator>
using namespace std;
int main() {
forward_list<char> trg{'a','b','c'};
forward_list<char> src{'1','2','3','4'};
auto before_first = src.begin();
auto last = find(src.begin(), src.end(), '4');
cout << "before_first = " << *before_first << ", last = " << *last << "\n";
// trg.splice(trg.begin(), src, before_first, last); // no such splice
auto end = last;
++end; // Ouch! splice has to find last again although I already had it :(
trg.splice_after(trg.begin(), src, before_first, end);
cout << "Target after splice:\n";
copy(trg.begin(), trg.end(), ostream_iterator<char>(cout," "));
cout << "\nSource after splice:\n";
copy(src.begin(), src.end(), ostream_iterator<char>(cout," "));
cout << endl;
}
输出:
before_first = 1, last = 4
Target after splice:
a 2 3 4 b c
Source after splice:
1