简体   繁体   中英

Getting all variables declared in a scope - C++

Is it possible to make a struct or class in C++ to get a list of the defined variables declared within a scope in C++. I don't want to hard-code these arrays.

For example, I have:

int a;
int b;
int c;
int d;

How can I get my program to print out what all the integers are in a program?

I want to be able to find the integers in the program that are incremented by one. (allints)++?

At some stage, you'll need to hardcode it. You can create a class that contains your ints and make a function to autoincrement all by one.

Something like:

class allints {
    int a, b, c, d;
    public:
        void autoincrement() {
            ++a, ++b, ++c, ++d;
        }
}

Or simply a vector of ints and loop it to autoincrement, as following:

allints = vector<int> (4, 0); //size 4, at the start value of 0.

void autoincrement(vector<int> v) {
    for(int i: v) ++i;
}

EDIT:

Noticing that you would be using structs or Classes, just group them in a vector and iterate them (like my 2nd example above)

If one needs to iterate over a bunch of objects of the same type the typical data structure one uses is an array (old school) or a collection of some kind, depending on secondary requirements like uniqueness, sortedness etc. (new school). This would work with arrays of built-in types as well as with arrays of structs.

Inside the class constructor I do vectorofPlatforms.pushback(this);

I have posted my own answer as none of you had thought of this approach, but I've giving you upvotes for your nice answers.

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