是否可以在C ++中为变量使用动态名称

是否可以在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.