【发布时间】:2025-11-29 09:15:01
【问题描述】:
下面我有一些代码,在最后一个 if 语句中我想搜索字母 B。但是,我想从找到 P 的位置开始搜索并递增,直到找到 B ,然后当它找到 B 我想执行一个方法。
我在我的代码中使用了注释来告诉你代码的去向。
所以步骤是
- 找到“P”的位置
- 从“P”的位置递增,直到找到“B”和执行方法
- 继续递增,直到到达向量的末尾,如果再次看到“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