std::list<T,Allocator>::splice

来自cppreference.com
< cpp‎ | container‎ | list
 
 
 
 
void splice( const_iterator pos, list& other );
(1) (C++26 起为 constexpr)
void splice( const_iterator pos, list&& other );
(2) (C++11 起)
(C++26 起为 constexpr)
void splice( const_iterator pos, list& other, const_iterator it );
(3) (C++26 起为 constexpr)
void splice( const_iterator pos, list&& other, const_iterator it );
(4) (C++11 起)
(C++26 起为 constexpr)
void splice( const_iterator pos, list& other,
             const_iterator first, const_iterator last );
(5) (C++26 起为 constexpr)
void splice( const_iterator pos, list&& other,
             const_iterator first, const_iterator last );
(6) (C++11 起)
(C++26 起为 constexpr)

other 将元素转移到 *this。元素会被插入到 pos 前。

如果满足以下任意条件,那么行为未定义:

  • pos 不在范围 [begin()end()) 中。
  • get_allocator() == other.get_allocator()false
1,2) 转移 other 的所有元素。操作后 other 变为空。
如果 *thisother 指代同一对象,那么行为未定义。
3,4) 转移 it 指向的元素。
*thisother 可以指代同一对象,并且在 pos == itpos == ++ittrue 时没有效果。
如果 it 不在范围 [begin()end()) 中,那么行为未定义。
5,6) 转移范围 [firstlast) 中的元素。
*thisother 可以指代同一对象。
如果满足以下任意条件,那么行为未定义:
  • [firstlast) 不是 other 中的有效范围
  • [firstlast) 中有不可解引用的迭代器。
  • pos[firstlast) 中。

没有迭代器或引用会失效。如果 *thisother 指代不同的对象,那么指向被转移的元素的迭代器现在指代到 *this 中,而不是到 other 中。

参数

pos - 将插入内容到它之前的元素
other - 要从它转移内容的另一容器
it - 要从 other 转移到 *this 的元素
first, last - 要从 other 转移到 *this 的元素范围的迭代器对

复杂度

1-4) 常数。
5,6) 如果 other*this 指代同一对象则为常数,否则与 std::distance(first, last) 成线性。

示例

#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (auto &i : list)
        ostr << ' ' << i;
 
    return ostr;
}
 
int main ()
{
    std::list<int> list1{1, 2, 3, 4, 5};
    std::list<int> list2{10, 20, 30, 40, 50};
 
    auto it = list1.begin();
    std::advance(it, 2);
 
    list1.splice(it, list2);
 
    std::cout << "list1:" << list1 << '\n';
    std::cout << "list2:" << list2 << '\n';
 
    list2.splice(list2.begin(), list1, it, list1.end());
 
    std::cout << "list1:" << list1 << '\n';
    std::cout << "list2:" << list2 << '\n';
}

输出:

list1: 1 2 10 20 30 40 50 3 4 5
list2:
list1: 1 2 10 20 30 40 50
list2: 3 4 5

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 250 C++98 到被移动的元素的引用或迭代器都会失效 它们指代或指向 *this 中相同的元素
N2525 C++98 get_allocator() != other.get_allocator()
的情况下无法保证在 O(1) 时间内完成转移
此时行为未定义

参阅

合并两个有序列表
(公开成员函数)
移除满足特定标准的元素
(公开成员函数)