“ while” /“ for”循环的替代方案是什么

Vla*_*mar 1 c++ loops

我有一门功课,我应该等到我写控制台“停止”一次又一次地做一些动作,但我不能使用forwhilegotoswitch[]typedef在我的所有代码。那么如何更换循环呢?

Ayx*_*xan 11

可以使用递归。此示例重复您输入的内容,直到您键入“ stop”作为示例:

#include <iostream>
#include <string>

void do_it()
{
  std::string s;
  std::cin >> s;
  if (s == "stop")
    return;
  std::cout << s << '\n';
  do_it();
}

int main()
{
  do_it();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

此处可能并非如此,但是递归有其缺点。一方面,它比简单的循环要慢,因为在像C ++这样的语言中,函数调用相对昂贵。如果它重复太多次,则可能导致堆栈溢出。话虽如此,该函数的递归版本有时可以更整洁,更易于阅读/理解。您可以在此处详细了解递归的优缺点。