10-6编写一个具有以下原型的函数模板:
template
void exchange (list
iterator p2);
该模板用于将l1链表的[p1,l1.end())区间和l2链表的[p2,l2.end())区间的内容
交换。在主函数中调用该模板,以测试该模板的正确性。
#include <iostream>
#include <list>
using namespace std;
// function template to exchange the contents of two list segments
template <class T>
void exchange (list<T>& l1, typename list<T>::iterator p1, list<T>& l2, typename list<T>::iterator p2) {
// swap the elements from p1 to l1.end() with the elements from p2 to l2.end()
while (p1 != l1.end() && p2 != l2.end()) {
swap(*p1, *p2);
p1++;
p2++;
}
// if one list segment is longer than the other, append the remaining elements to the other list
if (p1 != l1.end()) {
l2.splice(l2.end(), l1, p1, l1.end());
}
else if (p2 != l2.end()) {
l1.splice(l1.end(), l2, p2, l2.end());
}
}
// main function to test the template
int main() {
// create two lists of integers
list<int> l1 = {1, 2, 3, 4, 5};
list<int> l2 = {6, 7, 8};
// print the original lists
cout << "l1: ";
for (int x : l1) {
cout << x << " ";
}
cout << endl;
cout << "l2: ";
for (int x : l2) {
cout << x << " ";
}
cout << endl;
// get iterators to the second element of each list
auto p1 = l1.begin();
p1++;
auto p2 = l2.begin();
p2++;
// call the exchange template function
exchange(l1, p1, l2, p2);
// print the modified lists
cout << "After exchange:" << endl;
cout << "l1: ";
for (int x : l1) {
cout << x << " ";
}
cout << endl;
cout << "l2: ";
for (int x : l2) {
cout << x << " ";
}
cout << endl;
return 0;
}
标签:11,p2,p1,end,list,l2,l1,打卡
From: https://www.cnblogs.com/wlxdaydayup/p/17392130.html