2012-06-11 49 views
1

我试图在C++的功能,可以使一个新的整型变量根据已经在使用std::map提供了如何使用其他变量声明变量?

为如

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"; 
} 
+3

局部变量名只存在于编译时,所以这样的功能将没有用。也许你可以解释你的高层目标? – cdhowie

+0

这是错误的语言,你选择了。 – Griwes

+0

预处理器可以使用##将字符串连接到任何内容。 –

回答

4

看名称。它允许你创建键值对。在这种情况下,密钥将是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; 
} 
+1

好吧,'std :: pair'可以让你*创建*键值对。 'std :: map'可以让你在*值的前半部分查找*对。 – cdhowie

+1

'std :: pair'允许您创建“第一秒”对。 'pair :: first'作为Key和'pair :: second'作为Value的解释特定于'std :: map'。 – MSalters

1

由于没有人发布它作为答案,所以有时候定义一个宏来创建一个变量是很方便的。

#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;