Difference between std::swap and std::vector::swapin C++. But before discussing the difference, we must know about the std::swap and std::vector::swap in C++. What is std::swap?The utility function std::swap is defined in the C++ standard library's <algorithm> header. It allows swapping the values of two objects. Syntax:The syntax of std::swap is: It takes two arguments; both reference objects of type T. It swaps the values using move semantics or copy and assignment. Some key points about std::swap:
Some examples of using std::swap: Example:Let us take an example code in C++ that illustrates swapping two vectors using the std::swap() function. Output: Original Vector 1: 1 2 3 4 5 Original Vector 2: 10 20 30 40 50 Vectors after swapping: Vector 1 (after swap): 10 20 30 40 50 Vector 2 (after swap): 1 2 3 4 5 Explanation: In this example, the code defines two vectors, displays their original content, swaps them using std::swap(), and then displays the content of the vectors after the swap. Note that std::swap() is used to change all the vectors efficiently. What is std::vector::swap?The std::vector::swap member function of the std::vector class efficiently swaps the contents of one vector with another. Syntax:It has the following syntax: It takes one argument - a reference to another std::vector to swap contents with. Some key points about std::vector::swap:
Example usage:Example:The following C++ code demonstrates how to swap two vectors using std::vector::swap(). Output: Original Vector 1: 1 2 3 4 5 Original Vector 2: 10 20 30 40 50 Vectors after swapping: Vector 1 (after swap): 10 20 30 4 5 Vector 2 (after swap): 1 2 3 40 50 Explanation: Just like the previous example, the content of Vector 1 has been swapped with the range of Vector 2 using std::vector::swap(). Major key differences between std::swap and std::vector::swapHere is a table summarizing the key differences between std::swap and std::vector::swap:
In summary, std::swap works for generic object swapping, while std::vector::swap leverages the vector's internal structure for an optimized, speedy vector shuffle, avoiding reallocation. The latter does not break any existing references into the vectors. Conclusion:In conclusion, std::swap exchanges any two objects by utilizing copy/move operations, while vector::swap leverages the vector's internal structure to efficiently shuffle contents in constant O(1) time without invalidating iterators.
Next TopicHow to Square a Number in C++
|