简体   繁体   中英

Passing a variable to function for reference an array into

I need to call function which contains many cases.

I'd like to pass it a variable which can reference different arrays.

This example demonstrates more clearly what I'm trying to achieve:

void bob(int debut, int fin, string flag){
     string arrayflag = "pfhistory_FR_" + flag;
     for (i = debut; i < fin; i++){
         std::cout  << arrayflag[i].DP << endl                          
     }
 };

If you want a variable which can reference different array's, you are require a 2D array. A 2D array can be thought of as an array of arrays, and you can index the arrays using a variable.

Roughly speaking C++ is a statically-bound language. This means that objects are resolved at compile time, not run time. As such, what you're trying to do is not possible in C++, but has to be implemented manually. Something like this:

void bob(int debut, int fin, string flag){
     auto *arrayflag =
           flag == "1" ? prhistory_FR_1 :
           flag == "2" ? prhistory_FR_2 :
                         prhistory_FR_3;

     for (i = debut; i < fin; i++){
         std::cout  << arrayflag[i].DP << endl                          
     }
 };

But this has all the markings of XY problem . You probably are asking something completely different, except that you think that this approach is the answer to your real question. But it's not. Whatever you're trying to do, the real answer is most likely something else. You just need to figure out what you're really asking.

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