使用预处理器重新定义循环

min*_*rus 4 c++ c-preprocessor

我希望做一些有点邪恶的事情.我想重新定义for循环来修改条件.有没有办法做到这一点?

从GCC文档中,支持重新定义关键字:http://gcc.gnu.org/onlinedocs/cpp/Macros.html

我正在尝试做的是为C++制作一个"概率"包装器,看看我是否可以用它做任何有趣的事情.

#include <iostream>
#include <cstdlib>

#define P 0.85

#define RANDOM_FLOAT  ((float)rand()/(float)RAND_MAX)

#define RANDOM_CHANCE (RANDOM_FLOAT < P)

#define if(a) if((a) && RANDOM_CHANCE)

#define while(a) while((a) && RANDOM_CHANCE)


// No more for loops or do-while loops
#define do
#define goto

// Doesn't work :(
//#define for(a) for(a) if(!RANDOM_CHANCE) { break; } 


int main() {
    srand(time(NULL));

    //Should output a random list of Y's and N's
    for(int i=0; i < 100; ++i) {
        if(i < 100) {
            std::cout << "Y";
        } else {
            std::cout << "N";
        }
    }

    std::cout << std::endl;

    // Will loop for a while then terminate
    int j = 0;
    while(j < 100) {
        ++j;
        std::cout << j << "\n";
    }

   std::cout << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

可能更合理的用途是计算正在运行的程序中的循环迭代次数,例如通过映射

for(int i=0; i < 10; ++i)
Run Code Online (Sandbox Code Playgroud)

for(int i=0; i < 10; ++i, ++global_counter)
Run Code Online (Sandbox Code Playgroud)

是否有可能完成我想要做的事情?


编辑:感谢您的回复 - 我真的很感激!

我可以做的一件事就是模拟一个公平的硬币(有效地强制P为0.5),注意如果你有一个有偏见的硬币,Pr(HT)== Pr(TH).我没有发现这个技巧,但它很有用.这意味着你可以近似任何P的概率分布.

bool coin() {
  bool c1 = false;
  bool c2 = false;

  if(true) {
    c1 = true;
  }
  if(true) {
    c2 = true;
  }

  //If they have different faces.
  bool valid = (c1 && !c2) || (!c1 && c2);
  bool result = c1;

  if(valid) { return result; }

  return coin();
}
Run Code Online (Sandbox Code Playgroud)

Pla*_*ure 8

您是否尝试过elsefor循环中添加?这应该使它工作.

#define for(a) for(a) if(!RANDOM_CHANCE) { break; } else

for (int i = 0; i < 10; ++i)
{
    // do something
}

/* should roughly compile to:
for (int i = 0; i < 10; ++i) if(!RANDOM_CHANCE) { break; } else
{
    // do something
}

or (differing only in whitespace):

for (int i = 0; i < 10; ++i)
    if(!RANDOM_CHANCE)
    {
        break;
    }
    else
    {
        // do something
    }
*/
Run Code Online (Sandbox Code Playgroud)