how to swap values in c++ code example
Example 1: swap in cpp
int a{}, b{}, temp{};
cin >> a >> b;
temp = a;
a = b;
b = temp;
a = a ^ b;
b = a ^ b;
a = a ^ b;
swap(a, b);
cout << "a " << a << endl;
cout << "b " << b << endl;
Example 2: swap string c++
#include <iostream>
#include <string>
main ()
{
std::string buyer ("money");
std::string seller ("goods");
std::cout << "Before the swap, buyer has " << buyer;
std::cout << " and seller has " << seller << '\n';
seller.swap (buyer);
std::cout << " After the swap, buyer has " << buyer;
std::cout << " and seller has " << seller << '\n';
return 0;
}
Example 3: what did swap method return in c++
Return Value: The function does not return anything, it swaps the values of the two variables