C ++:创建变量的迭代 [英] C++ : Iteration to create variables

查看:56
本文介绍了C ++:创建变量的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道每次循环执行时是否有办法用新名称创建新变量.

I was just curious to know if there is way to create a new variable with a new name everytime a loop is executed.

例如:

#include <iostream>
int main()
{
    for (int x = 1 ; x<=5 ; x++)
       int a_x;
    return 0;
}

应使用名称a_1,a_2 ...... a_5

上面的代码仅显示我正在寻找的内容,不是答案.

The above code just shows what i am looking for and is not the answer.

编辑:寻找不使用数组的出路.

-具有学习意愿的C ++新手:)

推荐答案

否,无法(直接)执行您概述的操作.以下是几种可能的选择:

No, there is no way to do what you've outlined (directly). Here are several possible alternatives:

  1. 首先,如果不需要在循环外部访问变量",则只需使用普通的局部变量即可:

  1. First off, if you do not need the "variables" to be accessible outside the loop, just use a normal local variable:

for (int x = 1; x <= 5; ++x) {
  int a = whatever;  // This will be freshly redeclared & reinitialised in each iteration
}

  • 如果在编译时知道迭代的边界,则可以使用数组:

  • If the bounds of the iteration are known at compile time, you can use an array:

    std::array<int, 5> a;
    for (int x = 0; x < a.size(); ++x) {
      a[x];
    }
    

  • 如果仅在运行时知道边界,请使用动态数组:

  • If the bounds are only known at runtime, use a dynamic array:

    std::vector<int> a(the_runtime_size);
    for (int x = 0; x < a.size(); ++x) {
      a[x];
    }
    

  • 如果出于某种原因确实需要单个变量(并且您知道编译时的数字),则可以使用

  • If you really need individual variables for some reason (and you know the number at compile time), you could resort to preprocessor tricks with Boost.Preprocessor. But that is far above beginner level:

    #include <boost/preprocessor>
    
    #define DECLARE_MY_VARIABLE(z, idx, name) \
      int BOOST_PP_CAT(name, BOOST_PP_CAT(_, idx));
    
    BOOST_PP_REPEAT(5, DECLARE_MY_VARIABLE, a)
    

    上面的代码将扩展为:

    int a_0; int a_1; int a_2; int a_3; int a_4;
    

    您当然可以更进一步,以使每个变量具有不同的类型,或者通过名称而不是通过索引来命名.它将只需要更多的宏魔术.

    You could of course take this several steps further, to have each of the variables of a different type, or name them by names instead of by indices. It will just require more macro magic.

    免责声明:除非您非常清楚地知道需要使用此方法,否则请不要使用此方法.即使这样,在实际执行此操作之前,请重新考虑两次.如果您仍然这样做,请大量记录.这样的东西通常应该隐藏在图书馆的深处.干净的用户友好界面.

    Disclaimer: Do NOT use this approach unless you very clearly know you need it. Even then, reconsider twice before you actually do that. And if you still do, document it heavily. Stuff like this should generally be hidden deep inside a library under a nice & clean user-friendly interface.

    这篇关于C ++:创建变量的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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