S
subramanian100in
I want to write data stored in a container into standard output or an
output file using for_each algorithm. To acheive this, the following
program creates a function object of type 'Print'. The argument to the
'Print' class ctor is an ostream object. This function object is
passed as the third argument to 'for_each' algorithm. The overloaded
function call operator in the 'Print' class, writes the data passed to
it into the ostream member data of the function object.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
class Print
{
public:
explicit Print(ostream& arg);
template <typename T> bool operator()(const T& arg);
private:
ostream& os;
};
Print:rint(ostream& arg) : os(arg)
{
}
template <typename T> inline bool Print:perator()(const T& arg)
{
os << arg << endl;
return true;
}
int main()
{
typedef vector<int> Container;
Container c;
for (int i = 0; i != 10; ++i)
c.push_back(i);
for_each(c.begin(), c.end(), Print(cout));
ofstream ofs("Descending_order");
if (!ofs)
{
cout << "Could not create output file" << endl;
return EXIT_FAILURE;
}
for_each(c.rbegin(), c.rend(), Print(ofs));
return EXIT_SUCCESS;
}
This program works as expected. Is this approach of passing a function
object argument to for_each algorithm for printing the container data,
correct ? Kindly reply me if there is a better/cleaner solution and
please provide the same.
Thanks
V.Subramanian
output file using for_each algorithm. To acheive this, the following
program creates a function object of type 'Print'. The argument to the
'Print' class ctor is an ostream object. This function object is
passed as the third argument to 'for_each' algorithm. The overloaded
function call operator in the 'Print' class, writes the data passed to
it into the ostream member data of the function object.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
class Print
{
public:
explicit Print(ostream& arg);
template <typename T> bool operator()(const T& arg);
private:
ostream& os;
};
Print:rint(ostream& arg) : os(arg)
{
}
template <typename T> inline bool Print:perator()(const T& arg)
{
os << arg << endl;
return true;
}
int main()
{
typedef vector<int> Container;
Container c;
for (int i = 0; i != 10; ++i)
c.push_back(i);
for_each(c.begin(), c.end(), Print(cout));
ofstream ofs("Descending_order");
if (!ofs)
{
cout << "Could not create output file" << endl;
return EXIT_FAILURE;
}
for_each(c.rbegin(), c.rend(), Print(ofs));
return EXIT_SUCCESS;
}
This program works as expected. Is this approach of passing a function
object argument to for_each algorithm for printing the container data,
correct ? Kindly reply me if there is a better/cleaner solution and
please provide the same.
Thanks
V.Subramanian