C++ Macro for Sorting Three Integers: A Simple Solution
Here's a C++ macro example to sort three integers:
#include<iostream>
#define SORT_THREE(a, b, c) \
do { \
if (a > b) { \
std::swap(a, b); \
} \
if (a > c) { \
std::swap(a, c); \
} \
if (b > c) { \
std::swap(b, c); \
} \
} while(0)
int main() {
int x = 3, y = 1, z = 2;
std::cout << "Before Sorting: " << x << " " << y << " " << z << std::endl;
SORT_THREE(x, y, z);
std::cout << "After Sorting: " << x << " " << y << " " << z << std::endl;
return 0;
}
In this example, the SORT_THREE macro accepts three integer arguments (a, b, and c) and sorts them in ascending order. It leverages the std::swap function for value swapping when needed. The macro is enclosed in a do-while loop, ensuring it acts like a single statement.
原文地址: https://www.cveoy.top/t/topic/Jrv 著作权归作者所有。请勿转载和采集!