标准库提供std::advance
,但只将迭代器推进到给定的偏移量.
自己编写该算法非常简单:
template<class Iter, class T>
void advance_until(Iter& it, Iter end, T const& delim){
while(it != end && *it != delim)
++it;
}
Run Code Online (Sandbox Code Playgroud)
甚至:
template<class Iter, class T>
void unsafe_advance_until(Iter& it, T const& delim){
while(*it != delim)
++it;
}
Run Code Online (Sandbox Code Playgroud)
哪个会更接近模仿std::advance
行为方式.
用法示例:
std::string s("hello world!");
std::string::iterator it(s.begin());
advance_until(it, s.end(), 'w');
//unsafe_advance_until(it, 'w');
if(it != s.end())
std::cout << *it << '\n'; // prints 'w'
Run Code Online (Sandbox Code Playgroud)
但也许在标准库或Boost中已有类似的东西,所以我想我会问.
这通常被称为std::find()
:
std::string::iterator it = std::find(s.begin(), s.end(), 'w');
if (it == s.end()) { /* not found */ }
else { /* found *it */ }
Run Code Online (Sandbox Code Playgroud)
可以通过循环找到连续项:
while (it != s.end())
{
// ...
++it; // always valid
it = std::find(it, s.end(), 'w');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
83 次 |
最近记录: |