是否可以在C ++中为变量使用动态名称 [英] Is it possible to use dynamic name for variables in c++

查看:441
本文介绍了是否可以在C ++中为变量使用动态名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可以的话,我想使用动态名称。这里有一个关于我的意思的例子:

I'd like to use dynamic names if it is possible. Here an example about what I mean:

int sol1,sol2;
for(int i=1; i<3; i++){
   sol"i"=i*i;
   return max(sol1,sol2);
}

带有 sol i 我的意思是在第一个周期(当i = 1时) sol1 ,在第二个周期(当i =时) sol2 2)。
是否可能以类似的方式?

With sol"i" I mean sol1 in the first cycle (when i=1) and sol2 for the second (when i=2). Is this possibile in a similar way?

推荐答案

不可能不可能

可能最常见的方法是使用 vector

Probably the most common approach is to use a vector (or array) and index it:

std::vector<int> sol(2);
for (int i = 0; i < 2; ++i) {
    sol[i] = i * i;
}

另一种方法是使用 std :: map 将所需的名称映射到结果变量:

Another approach is to use a std::map to map the desired name to the resulting variable:

std::map<std::string, int> variables;
for (int i = 1; i < 3; ++i) {
    std::string varname = "sol" + std::to_string(i);
    variables[varname] = i * i;
}

但是请注意,这是一个非常慢的解决方案。我之所以仅提及它,是因为它允许您执行与原始示例相似的操作。改用向量/数组方法。

Note, however, that this is an extremely slow solution. I mention it only because it allows you to do something similar to your original example. Use the vector / array approach instead.

这篇关于是否可以在C ++中为变量使用动态名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆