简体   繁体   中英

Is it possible to swap the occurences of two variables using macros in C++?

I was working on a contest problem, where I had to initialize a vector in the following way:

vector<pair<int,int>> moves({{i,j}, {i,-j}, {-i,j}, {-i,-j}, 
                             {j,i}, {j,-i}, {-j,i}, {-j,-i}});

Although I know that this is not the best way and am aware of a number of different ways to accomplish this with minimal effort, I wonder if there is a way the C++ macros allow me to simply copy-paste the first four elements of the above vector to achieve the same in the following way:

vector<pair<int,int>> moves({{i,j}, {i,-j}, {-i,j}, {-i,-j},
#define i j 
#define j i
                             {i,j}, {i,-j}, {-i,j}, {-i,-j}
#undef i
#undef j
                             });

The above code obviously does not work because of circular referencing of the variables.

PS : Although Matteo Italia's answer is absolutely correct in the above context, I am more interested in knowing whether swapping occurences of variables using macros is possible in C++ or not and how, if possible?

If you really think it's such a saving, you can use a function-style macro and invoke it twice, swapping its arguments.

#define SIGN_COMB(a, b) {(a), (b)}, {(a), -(b)}, {-(a), (b)}, {-(a), -(b)}
vector<pair<int,int>> moves({SIGN_COMB(i, j), SIGN_COMB(j, i)})

The parentheses in the macro expansion as usual are to avoid surprises if expressions are passed as argument (if one passed in eg x+y , the negated terms would be -x+y instead if -(x+y) ).

Macros are Evil and not a good idea in this context. However, since that appears to be known and the question is more of an academic nature: think "define" rather than "swap". You can use neither " i " nor " j " as a macro's name since you want both to appear in the processed code. So introduce two new identifiers for your macros. Once you update the first four elements to use the new identifiers, you get to copy-and-paste them as requested.

vector<pair<int,int>> moves({
#define a i
#define b j
                             {a,b}, {a,-b}, {-a,b}, {-a,-b},
#undef a
#undef b
#define a j
#define b i
                             {a,b}, {a,-b}, {-a,b}, {-a,-b}
#undef a
#undef b
                             });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM