How to use: istreambuf_iterator

M

mathieu

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 ;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,264
Latest member
FletcherDa

Latest Threads

Top