只是为了完整起见,由于该标准没有提供现成的解决方案,这就是我的解决方案:
template<class _InIt, class _OutIt, class _Pr>
inline void copy_until (_InIt _First, _InIt _Last, _OutIt _Dest, _Pr _Pred) {
while ((_First != _Last) && _Pred(*_First)) {
*_Dest++ = *_First++;
}
}
这就是我使用它的方式:
copy_until(std::istreambuf_iterator<char>(is),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(os),
[] (char c) { return <some usefull condition here> });
例如,从输入流中读取仅包含 alnum 字符的字符串:
std::istream& operator>> (std::istream& is, std::string& n) {
std::ostringstream str;
copy_until(std::istreambuf_iterator<char>(is),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(str),
std::isalnum);
n = str.str();
return is;
}