How to use: istreambuf_iterator
Hi there,
I think I misunderstanded the use of istreambuf_iterator. I thought
I could use it this way (*). Which would allow me to skip the call to
vector::resize(). Could someone please let me know what is wrong in my
code. My goal is simply to skip the default initialization to 0 of the
std::vector which is compulsary for 'DoMethod1'.
At least on my OS: Debian & g++-4.2 -03, DoMethod2 is slower by a
factor of 3.
Thanks
-Mathieu
(*)
#include <vector>
#include <iterator>
#include <iostream>
#include <fstream>
void DoMethod1(std::ifstream &in, std::streampos length,
std::vector<char> & v)
{
in.seekg(0, std::ios::beg);
v.resize( length );
in.read(&v[0], length);
}
void DoMethod2(std::ifstream &in, std::streampos length,
std::vector<char> & v)
{
in.seekg(0, std::ios::beg );
v.reserve( length );
std::copy( std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
std::back_inserter(v)) ;
}
int main(int argc, char *argv[])
{
if( argc < 2 )
{
std::cerr << argc << std::endl;
return 1;
}
const char *filename = argv[1];
time_t start,end;
std::ifstream in( filename, std::ios::binary ) ;
in.seekg(0, std::ios::end );
std::streampos length = in.tellg();
std::vector<char> v2;
start = time(0);
DoMethod2( in, length, v2);
end = time(0);
std::cerr << "method2:" << (end - start) << std::endl;
std::vector<char> v1;
start = time(0);
DoMethod1( in, length, v1);
end = time(0);
std::cerr << "method1:" << (end - start) << std::endl;
in.close();
return 0 ;
}