Bulk operations will benefit from the stream iterators greatly. As it happens to be they behave like a container, so we can use them quite elgantly. They are fast for mass storage/retreival.
Tip:
- Don't forget to overload your extraction/insertion operators. It is crucial as you will obviously see.
- Learn to include the <iterator> header. The standard requires it, yet a only a relative few include them. The fact code often works without the include is bad luck: compiler designers mistake.
- Check out: istreambuf_iterator<> as well.
- Check out: back_insert_iterator<>() as well.
Code:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <iterator>
#include <algorithm>
// istream_iterator, ostream_iterator bulk operations demo.
// 1) We create a file of martian data, by stream a vector towards ostream.
// 2) Then we empty the vector.
// 3) We load the file back into the vector and view its contents.
using namespace std;
//--
struct Martian
{
int age_;
bool gender_;
string species_;
};
//--
ostream& operator<<(ostream& os, const Martian& md)
{
os<<md.age_<<" "<<md.gender_<<" "<<md.species_;
return os;
}
//--------------------------------------------------
istream& operator>>(istream& is, Martian& md)
{
is>>md.age_>>md.gender_;
//So the species (std::string) name can have spaces.
getline(is, md.species_);
return is;
}
//--------------------------------------------------
void save_db(vector<Martian>& mguide)
{
ofstream outfile("MartianData.txt");
copy(mguide.begin(), mguide.end(), ostream_iterator<Martian>(outfile, "\n") );
outfile.close();
}
//--------------------------------------------------
void open_db(vector<Martian>& mguide)
{
ifstream infile("MartianData.txt");
copy( istream_iterator<Martian>(infile), istream_iterator<Martian>(),
back_inserter(mguide) );
infile.close();
}
//--------------------------------------------------
int main(int argc, char *argv[])
{
Martian theMd;
vector<Martian> martianGuide;
//Let's create some martian info and dump it in a vector.
theMd.age_ = 320;
theMd.gender_ = false;
theMd.species_ = "Crater Planktons";
martianGuide.push_back(theMd);
theMd.age_ = 243;
theMd.gender_ = false;
theMd.species_ = "Mountain Worms";
martianGuide.push_back(theMd);
theMd.age_ = 211;
theMd.gender_ = true;
theMd.species_ = "Sky Fish";
martianGuide.push_back(theMd);
//Let's save it to a file.
save_db(martianGuide);
//Emtpy this vector.
martianGuide.erase(martianGuide.begin(), martianGuide.end() );
//Fill the vector again to verify correct storage and operator>> overload.
open_db(martianGuide);
copy(martianGuide.begin(), martianGuide.end(), ostream_iterator<Martian>(cout, "\n"));
return 0;
}