通过将变量名称“缝合”在一起来访问 C++ 中的变量

2024-03-14

假设我有一个变量:

 int fish5 = 7;

我可以通过连接术语“fish”和“5”来访问fish5吗?

理想的解决方案如下所示:

 printf("I am displaying the number seven: %i", fish + 5);

不,不完全是你想要的。但在您的示例中,您可以使用数组(仅当您想将变量名与数字连接时才有效):

int fish[6] = {0};
fish[5] = 7;

printf("I am displaying the number seven: %i", fish[5]);

也可以看看here http://en.cppreference.com/w/cpp/language/array有关 C++ 中数组的参考。

另一种解决方案是使用std::map相反,正如 Thrustmaster 在评论中指出的那样。

然后你可以写这样的东西:

#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, see here http://www.cplusplus.com/reference/map/map/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过将变量名称“缝合”在一起来访问 C++ 中的变量 的相关文章