是的。可以办到。但首先,我想向您展示简单而优雅的解决方案:
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]
}
我希望你能看到我向你展示的每次迭代都会变得更加复杂,基本上做同样的事情。
所以如果我给你看的第一个不是你想要的,我真的会重新考虑。
免责声明:未编译,未测试