C++ vector swap() 函数

定义和用法

swap() 函数用于交换两个向量的内容。

调用 swap() 函数后,每个向量将包含之前在另一个向量中的内容。

实例

交换两个向量的内容:

vector<string> cars = {"Volvo", "BMW", "Ford", "Tesla"};
vector<string> fruits = {"Apple", "Banana", "Cherry", "Orange"};

cars.swap(fruits);

cout << "汽车:\n";
for (string car : cars) {
  cout << car << "\n";
}

cout << "\n水果:\n";
for (string fruit : fruits) {
  cout << fruit << "\n";
}

亲自试一试

语法

vector.swap(vector other);

参数

参数 描述
other 必需。用于交换内容的另一个向量。

相关页面

教程:C++ 向量