Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > How to use: ist...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 1 Topic 44108 of 48011
Post > Topic >>

How to use: istreambuf_iterator

by mathieu <mathieu.malaterre@[EMAIL PROTECTED] > Mar 25, 2008 at 09:39 AM

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




 1 Posts in Topic:
How to use: istreambuf_iterator
mathieu <mathieu.malat  2008-03-25 09:39:06 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Mon Oct 13 3:59:24 CDT 2008.