如何使用std :: forward_list在恒定时间内进行范围拼接?

时间:2013-01-05 10:08:30

标签: c++ c++11 forward-list

我想拼接范围[first, last],两个端点都包含在内。我在 firstlast之前有元素的迭代器。我可以用splice_after()来做,但只能在线性时间内完成。

我相信这种拼接可以在不变的时间内完成。如何使用std::forward_list进行拼接?

如果问题不明确,这里显示我的问题的示例代码:

Live Work Space上的代码

#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 

1 个答案:

答案 0 :(得分:5)

forward_list的规范说明应该拼接范围(first, last),遗憾的是在O(1)时间内无法执行此操作,因为需要访问last-1这样做,获取last-1访问权限的唯一方法是从first向前迭代。

如果规范要拼接范围(first, last],则可以进行O(1)拼接。我知道目前的forward_list规范无法实现这一目标。

我认为这是一个缺陷。但是我已经尝试过但未能修复它:

http://cplusplus.github.com/LWG/lwg-defects.html#897

然而,问题在过去已经被逆转,特别是当投诉来自像你这样的非委员会成员时。提交投诉的方式是打开一个新问题,在适当时引用任何旧问题或相关问题。打开问题的说明是here

PS:问题上的+1。