【问题标题】:C++ search and execute method whenever a character is spotted发现字符时的 C++ 搜索和执行方法
【发布时间】:2025-11-29 09:15:01
【问题描述】:

下面我有一些代码,在最后一个 if 语句中我想搜索字母 B。但是,我想从找到 P 的位置开始搜索并递增,直到找到 B ,然后当它找到 B 我想执行一个方法。

我在我的代码中使用了注释来告诉你代码的去向。

所以步骤是

  1. 找到“P”的位置
  2. 从“P”的位置递增,直到找到“B”和执行方法
  3. 继续递增,直到到达向量的末尾,如果再次看到“B”,则再次执行相同的方法,依此类推

我目前的代码是:

std::vector<std::string> order;
std::vector<std::string>::iterator it;
std::vector<std::string> tempOrder;

order.push_back("V"); //V
order.push_back("I");//F
order.push_back("F");//I
order.push_back("N");//O
order.push_back("D");//O
order.push_back("W");//O
order.push_back("O");//O
order.push_back("P");//O
order.push_back("Y");//O
order.push_back("B");//O
order.push_back("L");//O
order.push_back("B");//O
order.push_back("R");//O
order.push_back("X");//O

if(order.front() == "V")
{
    it = find(order.begin(), order.end(), "I");
    ++it;
    std::string o = *it;
    DCS_LOG_DEBUG("NEXT 0 " << o);
    DCS_LOG_DEBUG("NEXT " << *it);


    int i = find(order.begin(), order.end(), "N") - order.begin();
    int pos = i;

    DCS_LOG_DEBUG("POS " << pos);

    for(int i1 = 0; i1 < pos; i1++)
    {
        //DCS_LOG_DEBUG("IN LINE " << order[i1]);

        if(order[i1] == "D" || order[i1] == "W" || order[i1] == "O" || order[i1] == "P")
        {
            DCS_LOG_DEBUG("It matches one of the above incorrect");

            break;
        }
        else
        {
            DCS_LOG_DEBUG("OK");
            break;
        }
    }

    std::vector<std::string>secondOrder;
    copy(order.begin() +  pos + 1, order.end(), std::back_inserter(secondOrder));


    if(find(secondOrder.begin(), secondOrder.end(),"P")- secondOrder.begin())
    {
        DCS_LOG_DEBUG("Found");
        int i1 = find(order.begin(), order.end(), "P") - order.begin();

        //HERE IS WHERE THE CODE WILL GO

    }
    else
    {
        DCS_LOG_DEBUG("NOT FOUND");
    }

}

【问题讨论】:

  • 你的代码没有迭代器吗?那不是更容易穿越吗?

标签: c++ if-statement for-loop while-loop


【解决方案1】:

所以把第二个逻辑放在一个循环中,直到它到达vector的末尾:

 if( (it = find(secondOrder.begin(), secondOrder.end(),"P") ) != secondOrder.end() )
 {
      DCS_LOG_DEBUG("Found");
      it1 = order.begin();
      while ( (it1 = find(it1, order.end(), "B")) != order.end() )
      {
         //code here
         //*it1 is the element you're looking for
      }
 }
 else
 {
      DCS_LOG_DEBUG("NOT FOUND");
 }

请注意,我使用的是迭代器,而不是索引。

另外,你的缩进很糟糕。

编辑:我看到您在我回答问题后更改了代码。逻辑保持不变。

【讨论】:

  • 抱歉it1 是从哪里来的,我会从 P 所在的位置循环到 secondOrder 的末尾而不是从order.begin()
  • @ShamariCampbell it1order 的迭代器。另外,由于您的问题不是很明确,我只是提供了逻辑。随意更改您认为合适的名称。
  • @Luchian Grigore:*.com/q/9530751/1155650用户转发问题
  • @Rohit 我知道,我投票决定关闭。显然,他自己并没有努力。一方面,我不会提供完整的解决方案。
  • 我正在努力,我整晚都在看这个!我只是不认为答案接近我想要的,但无论如何我将在我可以找到第一个 B 的那一刻重新开始,然后转到向量的末尾,但只要迭代器找到另一个字母它会多次输出我的错误语句我只想输出一次:)? @LuchianGrigore