Swap operation on a vector in C++
This post will discuss swap operation on a vector in C++.
Here’s a three-line implementation of the swap function in C using pointers.
|
1 2 3 4 5 6 |
void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } |
Let’s discuss various methods to do this in C++:
1. Using std::move function
We can use std::move introduced by the C++11 to swap two objects, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <vector> template <typename T> void swap(T &x, T &y) { T temp = std::move(x); x = std::move(y); y = std::move(temp); } /* // before C++11 template <typename T> void swap(T &x, T &y) { T temp = x; x = y; y = temp; }*/ int main() { std::vector<int> nums = { 0, 1, 2, 3, 4 }; int i = 2, j = 3; swap(nums[i], nums[j]); for (int i: nums) { std::cout << i << ' '; } return 0; } |
Output:
0 1 3 2 4
2. Using std::swap function
The standard solution is to use the std::swap algorithm defined in the <utility> header (in C++11). It works by swapping the values of two objects.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> #include <utility> int main() { std::vector<int> nums = { 0, 1, 2, 3, 4 }; int i = 2, j = 3; std::swap(nums[i], nums[j]); for (int i: nums) { std::cout << i << ' '; } return 0; } |
Output:
0 1 3 2 4
3. Using std::iter_swap function
Another alternative is to use the std::iter_swap algorithm defined in the <algorithm> header. It works by swapping the values of objects pointed to by specified iterators.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <vector> #include <iterator> #include <algorithm> int main() { std::vector<int> nums = { 0, 1, 2, 3, 4 }; int i = 2, j = 3; auto itr_i = std::next(nums.begin(), i); auto itr_j = std::next(nums.begin(), j); std::iter_swap(itr_i, itr_j); for (int i: nums) { std::cout << i << ' '; } return 0; } |
Output:
0 1 3 2 4
That’s all about swap operation on a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)