简体   繁体   中英

Using a variable's value to refer to a variable's name in C++

I have a function that looks like this,

void Parser::executeSearchQuery(string field, 
                                string value, 
                                Data* &temp, 
                                int arraySize)
{
    for (int i = 0; i<arraySize; i++) {
        if (temp[i].name==value) {
            cout << temp[i].name << endl;
            cout << temp[i].type << endl;
            cout << temp[i].length << endl;
        }
    }
}

I want the function to search a given field for a given value. I want the string 'field' to be the variable that determines what field to compare against a value but I'm not exactly sure how to do that. Having temp[i].field doesn't work, nor does name==value because it compares the string, not that name of the variable the string has.

I could use if statements but I was hoping for something more flexible, for when I introduce more fields and expand it.

So, say I have the following data,

temp 0 is John, 1, 5
temp 1 is Matt, 2, 7
temp 2 is Phil, 1, 6

The three fields are Name, Type and Length.

I want the function to take a field name into 'field' and display all results where the field equals the 'value', also submitted by the user. But I don't know how to handle the 'field' bit.

If I understand correctly, you are asking for "variable variables", like PHP's "$$x" syntax. This isn't available in C++ because it needs to know what variable you are referring to at compile time, not run time.

Your only alternatives are to use normal conditional statements ( if , switch ), or to store the data in a map (aka dictionary, associative array) instead of a fixed data structure.

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