我想拼接範圍[first, last]
,包括兩個端點。我有first
和last
之前的元素的迭代器。我可以用splice_after()
做到這一點,但只能在線性時間。如何在std :: forward_list的恆定時間範圍內拼接?
我相信這種拼接可以在不變的時間完成。如何使用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
gcc libstdC++在常量時間內執行此操作,但visual C++沒有。 ([why](http://msdn.microsoft.com/en-us/library/vstudio/ee373562%28v=vs.110%29.aspx):_如果第三個成員函數插入N個元素,並且&Right!= this ,類迭代器的對象增加N次_) – neam
@tim你在哪裏gcc做到這一點?請給出鏈接。 – Ali
[這裏](http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00484.html#a90ae2ddea9cebf2b29f7399683dc3e20)(對不起,我忘了給你的鏈接) – neam