容器库:std::list<T,Allocator>::splice

it2026-09-25  14

void splice( const_iterator pos, list& other );

(1) 

void splice( const_iterator pos, list&& other );

(1)(C++11 起)

void splice( const_iterator pos, list& other, const_iterator it );

(2) 

void splice( const_iterator pos, list&& other, const_iterator it );

(2)(C++11 起)

void splice( const_iterator pos, list& other,              const_iterator first, const_iterator last);

(3) 

void splice( const_iterator pos, list&& other,              const_iterator first, const_iterator last );

(3)(C++11 起)

从一个 list 转移元素给另一个。

不复制或移动元素,仅重指向链表结点的内部指针。若 get_allocator() != other.get_allocator() 则行为未定义。没有迭代器或引用被非法化,指向被移动元素的迭代器保持合法,但现在指代到 *this 中,而非到 other 中。

1) 从 other 转移所有元素到 *this 中。元素被插入到 pos 所指向的元素之前。操作后容器 other 变为空。若 other 与 *this 指代同一对象则行为未定义。

2) 从 other 转移 it 所指向的元素到 *this 。元素被插入到 pos 所指向的元素之前。

3) 从 other 转移范围 [first, last) 中的元素到 *this 。元素被插入到 pos 所指向的元素之前。若 pos 是范围 [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); //迭代器it指向list1中的元素3 list1.splice(it, list2); //将list2中的元素转移到it所指元素位置的前面,转移后为1,2,10,20,30,40,50,3,4,5,而此时list2已为空。 std::cout << "list1: " << list1 << "\n"; std::cout << "list2: " << list2 << "\n"; list2.splice(list2.begin(), list1, it, list1.end()); //将list1中从迭代器it开始到list1结束的所有元素转移到list2中去 std::cout << "list1: " << list1 << "\n"; std::cout << "list2: " << list2 << "\n"; }

运行结果:

唯一需要注意的就是 splice有点像std::move,是转移,不是复制。

最新回复(0)