A
Alex Buell
I've just written the below as an exercise (don't worry about the lack
of checking), but I was wondering why I needed to write a struct with
an operator() as a parameter to supply to the STL transform() function?
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
struct lowercase
{
string operator()(const string& s)
{
string lower(s);
for (size_t i = 0; i < s.length(); ++i)
lower = tolower(lower);
return lower;
}
};
int main(int argc, char* argv[])
{
if (argc > 1)
{
ifstream in(argv[1]);
vector<string> vs;
copy(istream_iterator<string>(in),
istream_iterator<string>(), back_inserter(vs)); transform(vs.begin(),
vs.end(), vs.begin(), lowercase()); sort(vs.begin(), vs.end());
vector<string>::iterator it = unique(vs.begin(), vs.end
()); vs.resize(it - vs.begin());
copy(vs.begin(), vs.end(), ostream_iterator<string>
(cout, "\n")); }
}
of checking), but I was wondering why I needed to write a struct with
an operator() as a parameter to supply to the STL transform() function?
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
struct lowercase
{
string operator()(const string& s)
{
string lower(s);
for (size_t i = 0; i < s.length(); ++i)
lower = tolower(lower);
return lower;
}
};
int main(int argc, char* argv[])
{
if (argc > 1)
{
ifstream in(argv[1]);
vector<string> vs;
copy(istream_iterator<string>(in),
istream_iterator<string>(), back_inserter(vs)); transform(vs.begin(),
vs.end(), vs.begin(), lowercase()); sort(vs.begin(), vs.end());
vector<string>::iterator it = unique(vs.begin(), vs.end
()); vs.resize(it - vs.begin());
copy(vs.begin(), vs.end(), ostream_iterator<string>
(cout, "\n")); }
}