通过“拼接”访问C ++中的变量它的名字在一起 [英] Accessing a variable in C++ by "stitching" its name together
本文介绍了通过“拼接”访问C ++中的变量它的名字在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个变量:
int fish5 = 7;
我可以通过连接术语fish和5来访问fish5吗?
Can I access fish5 by concatenation of the term "fish" and "5" somehow?
一个理想的解决方案如下所示:
An ideal solution would look something like this:
printf("I am displaying the number seven: %i", fish + 5);
推荐答案
不,不是你想要的。但在你的例子中,你可以使用一个数组(只有当你想用一个数字连接一个变量名时才有效):
No, not exactly what you want. But in your example, you can use an Array (only works if you want to concatenate an variablename with an number):
int fish[6] = {0};
fish[5] = 7;
printf("I am displaying the number seven: %i", fish[5]);
See also here for an reference to Arrays in C++.
另一种解决方案是使用一个语言/数组rel =nofollow
Another solution would be using a std::map
instead, like pointed out by Thrustmaster in the comments.
然后你可以写如下:
#include <map>
#include <string>
int main(int argc, char* argv[]){
std::map<std::string, int> map;
map.insert(std::make_pair("fish5", 7));
printf("I am displaying the number seven: %d", map[std::string("fish") + std::to_string(5)]);
return 0;
}
有关 std :: map
,请参阅这里。
这篇关于通过“拼接”访问C ++中的变量它的名字在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文