C++ List 库 - swap() 函数
描述
C++ 函数 std::list::swap() 与另一个交换第一个列表的内容。 如有必要,此功能会更改列表的大小。
声明
以下是 std::list::swap() 函数形式 std::list 头的声明。
C++98
void swap (list& x);
参数
x − 另一个相同类型的列表对象。
返回值
None.
异常
此成员函数从不抛出异常。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 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; l1.swap(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