如何使用另一个变量声明一个变量

How to declare a variable using another variable?

本文关键字:变量 一个 声明 何使用 另一个      更新时间:2023-10-16

我正在尝试在C++中创建一个函数,该函数可以根据提供的名称创建一个新的整数类型变量

例如

void my_variable(char name)
{
    int "something here" = 1;  // i am figuring out what to write 
    // there so that it makes a variable from that character that i have sent
    cout << "something here";
}

看看使用 std::map .它允许您创建键值对。在此实例中,键将name,值将为 int。以下代码片段演示了如何创建地图,填充地图,然后基于键搜索值。

void my_function(std::string name)
{
    std::map<std::string, int> myMap;
    myMap[name] = 1;  // 
    cout << "Key " << name << " holds " << paramMap.find(name)->second << std::endl;
}

由于没有人将其作为答案发布,因此有时定义宏来创建变量很方便。

#define DEFINE_HELPER(x) Helper helper_##x = Helper(#x)
#define HELPER(x) (&helper_##x)
struct Helper {
    std::string name;
    Helper (const char *s) : name(s) {}
};
DEFINE_HELPER(A);
DEFINE_HELPER(B);
std::cout << HELPER(A)->name << std::endl;
相关文章: