我想用std::find_if
遍歷std::streambuf
的內容相反。這包括從std::istream_iterator
或std::istreambuf_iterator
構建std::reverse_iterator
。不幸的是,試圖做到這一點,如下面的代碼示例所示,會導致編譯錯誤。我怎樣才能使這個工作?如果有必要,使用Boost的解決方案會很好。迭代流逆向
#include <cstddef>
#include <fstream>
#include <iterator>
template <class Iterator>
static std::reverse_iterator<Iterator>
make_reverse_iterator(Iterator i)
{
return std::reverse_iterator<Iterator>(i);
}
int main()
{
std::ifstream is{"foo.txt", std::ios::binary};
std::istreambuf_iterator<char> i{is};
auto r = make_reverse_iterator(i);
// Error =(
*r;
return EXIT_SUCCESS;
}
這裏報道編譯錯誤的g++-4.8.1
:
In file included from /opt/local/include/gcc48/c++/bits/stl_algobase.h:67:0,
from /opt/local/include/gcc48/c++/bits/char_traits.h:39,
from /opt/local/include/gcc48/c++/ios:40,
from /opt/local/include/gcc48/c++/istream:38,
from /opt/local/include/gcc48/c++/fstream:38,
from ri.cpp:9:
/opt/local/include/gcc48/c++/bits/stl_iterator.h: In instantiation of 'std::reverse_iterator<_Iterator>::reference std::reverse_iterator<_Iterator>::operator*() const [with _Iterator = std::istream_iterator<char>; std::reverse_iterator<_Iterator>::reference = const char&]':
ri.cpp:24:3: required from here
/opt/local/include/gcc48/c++/bits/stl_iterator.h:163:10: error: no match for 'operator--' (operand type is 'std::istream_iterator<char>')
return *--__tmp;
^
感謝您的幫助!
請告訴我編譯錯誤? – Borgleader
@Borgleader我剛剛編輯了問題以包含編譯錯誤。 –
向後迭代流?並非所有的流都能夠「倒帶」,所以我懷疑是否有一種非常通用的方式來做到這一點。 – John3136