Swap funkcija

Napisati funkciju:

template <typename T>
void swap(T &a, T &b);

koja menja vrednosti promenljivih a i b tipa T.

Test

#include <iostream>
#include <string>

namespace matf {

	template <typename T>
	void swap(T &a, T &b)
	{
        // Ovde ide vaša implementacija
	}

} // namespace matf

int main(void)
{
	int x = 5;
	int y = 10;

	std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
	// Output: Before swap: x = 5, y = 10
	matf::swap(x, y);
	std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
	// Output: After swap: x = 10, y = 5


	std::string str1 = "Hello";
	std::string str2 = "World";
	
	std::cout << "Before swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;
	// Output: Before swap: str1 = Hello, str2 = World
	matf::swap(str1, str2);
	std::cout << "After swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;
	// Output: After swap: str1 = World, str2 = Hello

	std::pair<int, std::string> p1 = {1, "one"};
	std::pair<int, std::string> p2 = {2, "two"};
	std::cout << "Before swap: p1 = (" << p1.first << ", " << p1.second << "), p2 = ("
			  << p2.first << ", " << p2.second << ")" << std::endl;
	// Output: Before swap: p1 = (1, one), p2 = (2, two)
	matf::swap(p1, p2);
	std::cout << "After swap: p1 = (" << p1.first << ", " << p1.second << "), p2 = ("
			  << p2.first << ", " << p2.second << ")" << std::endl;
	// Output: After swap: p1 = (2, two), p2 = (1, one)

	return 0;
}

Rešenje

main.cpp

#include <iostream>
#include <string>

namespace matf {

	template <typename T>
	void swap(T &a, T &b)
	{
		T temp = a;
		a = b;
		b = temp;
	}

} // namespace matf

int main(void)
{
	int x = 5;
	int y = 10;

	std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
	// Output: Before swap: x = 5, y = 10
	matf::swap(x, y);
	std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
	// Output: After swap: x = 10, y = 5


	std::string str1 = "Hello";
	std::string str2 = "World";
	
	std::cout << "Before swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;
	// Output: Before swap: str1 = Hello, str2 = World
	matf::swap(str1, str2);
	std::cout << "After swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;
	// Output: After swap: str1 = World, str2 = Hello

	std::pair<int, std::string> p1 = {1, "one"};
	std::pair<int, std::string> p2 = {2, "two"};
	std::cout << "Before swap: p1 = (" << p1.first << ", " << p1.second << "), p2 = ("
			  << p2.first << ", " << p2.second << ")" << std::endl;
	// Output: Before swap: p1 = (1, one), p2 = (2, two)
	matf::swap(p1, p2);
	std::cout << "After swap: p1 = (" << p1.first << ", " << p1.second << "), p2 = ("
			  << p2.first << ", " << p2.second << ")" << std::endl;
	// Output: After swap: p1 = (2, two), p2 = (1, one)

	return 0;
}