简体   繁体   English

在C ++中使用变量的值引用变量的名称

[英]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. 我希望字符串“ field”是一个变量,该变量确定将哪个字段与值进行比较,但是我不确定如何做到这一点。 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. 拥有temp [i] .field无效,name == value也无效,因为它比较字符串,而不是字符串具有的变量名称。

I could use if statements but I was hoping for something more flexible, for when I introduce more fields and expand it. 我可以使用if语句,但是当我引入更多字段并对其进行扩展时,我希望有一些更灵活的方法。

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. 如果我理解正确,那么您将要求使用“变量变量”,例如PHP的“ $$ x”语法。 This isn't available in C++ because it needs to know what variable you are referring to at compile time, not run time. 这在C ++中不可用,因为它需要知道在编译时(而不是运行时)所指的变量。

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. 您唯一的选择是使用常规条件语句( ifswitch ),或将数据存储在映射表(aka字典,关联数组)中,而不是固定的数据结构中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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