gpt4 book ai didi

c++ - 通过 "stitching"访问 C++ 中的变量及其名称

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:18 24 4
gpt4 key购买 nike

假设我有一个变量:

 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获取对 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 的更多信息,请参阅 here .

关于c++ - 通过 "stitching"访问 C++ 中的变量及其名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24546385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com