C++ vector swap() function
Example
Swap the contents of two vectors:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
vector<string> fruits = {"Apple", "Banana", "Cherry", "Orange"};
cars.swap(fruits);
cout << "Cars:\n";
for (string car : cars) {
cout << car << "\n";
}
cout << "\nFruits:\n";
for (string fruit : fruits) {
cout << fruit << "\n";
}
Try it Yourself »
Definition and Usage
The swap()
function swaps the contents of two vectors. After the swap()
function is called, each vector will have the contents that were previously in the other vector.
Syntax
vector.swap(vector other);
Parameter Values
Parameter | Description |
---|---|
other | Required. A vector with which to swap contents. |
Related Pages
Read more about vectors in our Vector Tutorial.