C++ List 库 - swap() 函数
描述
C++ 函数 std::list::swap() 与另一个交换第一个列表的内容。 如有必要,此功能会更改列表的大小。
声明
以下是 std::list::swap() 函数形式 std::list 头的声明。
C++98
template <class T, class Alloc> void swap (list<T,Alloc>& first, list<T,Alloc>& second);
参数
first − 第一个列表对象。
second − Second list object.
返回值
None.
异常
此函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::list::swap() 函数的用法。
#include <iostream> #include <list> using namespace std; int main(void) { list<int> l1 = {1, 2, 3}; list<int> l2 = {10, 20, 30, 40, 50}; cout << "List l1 contains following elements before swap operation" << endl; for (auto it = l1.begin(); it != l1.end(); ++it) cout << *it << endl; cout << "List l2 contains following elements before swap operation" << endl; for (auto it = l2.begin(); it != l2.end(); ++it) cout << *it << endl; swap(l1, l2); cout << "List l1 contains following elements after swap operation" << endl; for (auto it = l1.begin(); it != l1.end(); ++it) cout << *it << endl; cout << "List l2 contains following elements after swap operation" << endl; for (auto it = l2.begin(); it != l2.end(); ++it) cout << *it << endl; return 0; }
让我们编译并运行上面的程序,这将产生以下结果 −
List l1 contains following elements before swap operation 1 2 3 List l2 contains following elements before swap operation 10 20 30 40 50 List l1 contains following elements after swap operation 10 20 30 40 50 List l2 contains following elements after swap operation 1 2 3