Archive for the ‘Code Plate’ Category

Danny Kalev writes :

  • Bulk I/O is a strenuous operation in terms of performance and resource allocation.
  • With the <iterator> library, the system can optimize your code as it conceptually performs an I/O operation in one shot.
  • Use of stream iterators provides more flexibility because it allows you to switch from one data source or target to another almost seamlessly (e.g. cin, cout, fstream or sstream).

He summarises as

  1. Treat data sources as input streams and targets as output streams.
  2. Create iterators that point to these streams.
  3. Use an algorithm or a container to transfer data from a source to a target

Examples of some better codes

How to write to cout using an ostream_iterator:

#include <iterator>
#include <iostream>
using namespace std;

int main()
{
ostream_iterator<int> os(cout); //bind iterator to cout
*os=10; //causes cout<<10
os++; //prepare for the next output operation
*os=5; //cout<<5
}

cin and cout with istream and ostream respectively:

#include <algorithm> //std::copy()
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
std::copy(istream_iterator<int> (cin),
istream_iterator<int> (),
ostream_iterator<int> (cout, ” “));
}

Dumping a container to cout:

void func()
{
vector<int> vi(10,35); //fill with 10 int of the value 35
//write contents of vi to cout, each number on a new line
std::copy(vi.begin(),
vi.end(),
ostream_iterator<int> (cout, “\n”));
}

Writing a container to a file:

void f(const vector<int> &vi)
{
//open a file in write mode
ofstream vi_dump(“vi.txt”);
if (!vi_dump) //failure?
{
cerr<<“couldn’t open file”;
exit(1);
}
copy(vi.begin(),
vi.end(),
ostream_iterator<int> (vi_dump, ” “));
}

Writing a stream to a container:

#include<vector>
#include<fstream>
#include<algorithm>
#include<cstdlib>
#include<iostream>
using namespace std;
int main() {
vector<int> vi;//vector to be filled
ifstream vi_dump(“vi.txt”); //open for read
if (!vi_dump) {
cerr<<“couldn’t open file”;
exit(1);
}

copy(istream_iterator<int> (vi_dump), istream_iterator<int> (), back_inserter(vi));
}

Advertisements