list的splice方法[通俗易懂]

2022-11-08 16:20:54 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

代码语言:javascript复制
#include <iostream>
#include <list>

using namespace std;

int main ()
{
  std::list<int> mylist1, mylist2;
  std::list<int>::iterator it;

  // set some initial values:
  for (int i=1; i<=4;   i)
     mylist1.push_back(i);     
     
  cout << "mylist1 contains:"; 
  for (it=mylist1.begin(); it!=mylist1.end();   it)
    cout << ' ' << *it;
  cout << endl;  // mylist1: 1 2 3 4

  for (int i=1; i<=3;   i)
     mylist2.push_back(i*10);  
     
  cout << "mylist2 contains:";
  for (it=mylist2.begin(); it!=mylist2.end();   it)
    cout << ' ' << *it;
  cout <<endl; // mylist2: 10 20 30

  it = mylist1.begin();
    it; 
  cout<<"it: "<<*it<<endl;    // points to 2

  mylist1.splice (it, mylist2); //第一种用法,list1调用splice方法,将list2中的元素插入到it前面,清空list2链表元素 
  								// mylist1: 1 10 20 30 2 3 4
                                // mylist2 (empty)
                                // "it" still points to 2 (the 5th element)
  cout<<"it: "<<*it<<endl;    // points to 2
  /*cout << "mylist1 contains:";
  for (it=mylist1.begin(); it!=mylist1.end();   it)
    cout << ' ' << *it;
  cout << endl;

  cout << "mylist2 contains:";
  for (it=mylist2.begin(); it!=mylist2.end();   it)
    cout << ' ' << *it;
  cout << endl;*///这个遍历改变了it所指的值 
  
  mylist2.splice (mylist2.begin(),mylist1, it);//第二种用法,list2调用splice方法,将list1中的单个元素插入到list2位置的前面 
                                // mylist1: 1 10 20 30 3 4
                                // mylist2: 2
                                // "it" is now invalid.
  it = mylist1.begin();
  advance(it,3);           // 迭代器递增函数,"it" points now to 30

  mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());//第三种用法,list1调用splice方法,将list1的it位置到end位置插入到list1的begin前面 
                                // mylist1: 30 3 4 1 10 20

  cout << "mylist1 contains:";
  for (it=mylist1.begin(); it!=mylist1.end();   it)
    cout << ' ' << *it;
  cout << endl;

  cout << "mylist2 contains:";
  for (it=mylist2.begin(); it!=mylist2.end();   it)
    cout << ' ' << *it;
  cout << endl;

  return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

0 人点赞