【问题标题】:How can I get out of the loop and continue the loop again?我怎样才能摆脱循环并再次继续循环?
【发布时间】:2017-09-18 11:33:42
【问题描述】:

我想写一个程序来完成下面的任务:


我有一个整数数组,

我,作为用户,给出一个整数s(如单词搜索),

我希望它做一个线性搜索并在数组中找到s

可能有多个单元格包含所需的s

代码应该从单元格0开始,搜索,在n_th单元格中找到s

在输出中显示n

然后跳出循环,到程序的另一部分去一个标签

然后返回循环搜索单元格,从 n+1_th 个单元格到末尾。

我使用 goto label 做到了这一点,但我还有其他方法可以做到吗?

【问题讨论】:

  • @Kiarash 是对的:OP 想要的本质上是一种在 C++ 中使用迭代器协程的方法(参见 Python、C#、...)。

标签: c++ arrays loops


【解决方案1】:

是的。可以办到。但首先,我想向您展示简单而优雅的解决方案:

std::vector<int> v = {....};
int to_search = ...;

for (auto elem : v)
{
  if (e == to_search)
  {
     // do something
  }
}

你确定这不是你真正需要的吗?


现在到您的实际要求:

template <class It, class T>
It find_next(It begin, It end, T to_search)
{
   for (auto it = begin; it != end; ++it)
   {
      if (*it == to_search)
        return it;
   }
   return end;
}
std::vector<int> v = {....};
int to_search = ...;

auto it = v.begin();

while ((it = find_next(it, v.end(), to_search)) != v.end())
{
   // do something with *it
}

你真的很想使用索引,很容易适应:

int find_next(const std::vector<int>& v, int begin, int end, int to_search)
{
   for (int i = begin; i != end; ++i)
   {
      if (v[i] == to_search)
        return i;
   }
   return end;
}
std::vector<int> v = {....};
int to_search = ...;

int from = 0;

while ((from = find_next(v, from, v.size(), to_search)) != v.size())
{
   // do something with v[from]
}

现在如果你真的想要原始循环而不是函数,当然也可以这样做:

std::vector<int> v = {....};
int to_search = ...;

int from = 0;

while (true)
{
   for (; from < v.size(); ++from)
   {
     if (v[from] == to_search)
       break;
   }

   if (from == v.size())
      break;

   // do something with v[from]
}

我希望你能看到我向你展示的每次迭代都会变得更加复杂,基本上做同样的事情。

所以如果我给你看的第一个不是你想要的,我真的会重新考虑。


免责声明:未编译,未测试

【讨论】:

  • 你有一个错字:它应该是v.end(),而不是while条件中的it.end()
  • 我做错了吗?很有可能,我有点赶时间。如果没有,我很想知道你为什么不喜欢这个答案。 @SingerOfTheFall ty,已更正。
【解决方案2】:

两种方法的示例,假设它是您感兴趣的索引。

找到元素时调用函数:

void search(const std::vector<int>& v, int x, std::function<void(int)> index_handler)
{
    for (int i = 0; i < v.size(); ++i)
    {
        if (v[i] == x)
        {
            index_handler(i);
        }
    }
}

让调用者确定起点(如std::string::find):

int search_2(const std::vector<int>& v, int x, int start)
{
    for (int i = start; i < v.size(); ++i)
    {
        if (v[i] == x)
        {
            return i;
        }
    }
    return -1;
}

使用示例:

int main()
{
    // Method 1
    std::vector<int> vs = { 1, 2, 1, 2, 1, 2, 3};
    search(vs, 2, [](int i) { std::cout << "found at index " << i << '\n'; });

    // Method 2
    int index = search_2(vs, 2, 0);
    while (index >= 0)
    {
        std::cout << "found at index " << index << '\n';
        index = search_2(vs, 2, index + 1);
    }
}

第二种方法更灵活,但也更混乱,更容易出错。

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2019-07-13
    相关资源
    最近更新 更多