Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
B.Eckel - Thinking in C++, Vol.2, 2nd edition.pdf
Скачиваний:
50
Добавлен:
08.05.2013
Размер:
2.09 Mб
Скачать

LSI blank(LSI begin, LSI end) { return find_if(begin, end,

mem_fun_ref(&string::empty));

}

int main(int argc, char* argv[]) { requireArgs(argc, 1);

ifstream in(argv[1]); assure(in, argv[1]); list<string> ls; string s; while(getline(in, s))

ls.push_back(s);

LSI lsi = blank(ls.begin(), ls.end()); while(lsi != ls.end()) {

*lsi = "A BLANK LINE";

lsi = blank(lsi, ls.end());

}

string f(argv[1]); f += ".out";

ofstream out(f.c_str()); copy(ls.begin(), ls.end(),

ostream_iterator<string>(out, "\n")); } ///:~

The blank( ) function uses find_if( ) to locate the first blank line in the given range using mem_fun_ref( ) with string::empty( ). After the file is opened and read into the list, blank( ) is called repeated times to find every blank line in the file. Notice that subsequent calls to blank( ) use the current version of the iterator so it moves forward to the next one. Each time a blank line is found, it is replaced with the characters “A BLANK LINE.” All you have to do to accomplish this is dereference the iterator, and you select the current string.

SGI extensions

The SGI STL (mentioned at the end of the previous chapter) also includes additional function object templates, which allow you to write expressions that create even more complicated function objects. Consider a more involved program which converts strings of digits into floating point numbers, like PtrFun2.cpp but more general. First, here’s a generator that creates strings of integers that represent floating-point values (including an embedded decimal point):

//: C05:NumStringGen.h

//A random number generator that produces

//strings representing floating-point numbers

Chapter 15: Multiple Inheritance

279

#ifndef NUMSTRINGGEN_H #define NUMSTRINGGEN_H #include <string> #include <cstdlib> #include <ctime>

class NumStringGen {

const int sz; // Number of digits to make public:

NumStringGen(int ssz = 5) : sz(ssz) { std::srand(std::time(0));

}

std::string operator()() {

static char n[] = "0123456789"; const int nsz = 10;

std::string r(sz, ' '); for(int i = 0; i < sz; i++)

if(i == sz/2)

r[i] = '.'; // Insert a decimal point else

r[i] = n[std::rand() % nsz]; return r;

}

};

#endif // NUMSTRINGGEN_H ///:~

You tell it how big the strings should be when you create the NumStringGen object. The random number generator is used to select digits, and a decimal point is placed in the middle.

The following program (which works with the Standard C++ STL without the SGI extensions) uses NumStringGen to fill a vector<string>. However, to use the Standard C library function atof( ) to convert the strings to floating-point numbers, the string objects must first be turned into char pointers, since there is no automatic type conversion from string to char*. The transform( ) algorithm can be used with mem_fun_ref( ) and string::c_str( ) to convert all the strings to char*, and then these can be transformed using atof:

//: C05:MemFun3.cpp // Using mem_fun()

#include "NumStringGen.h" #include <algorithm> #include <vector> #include <string> #include <iostream> #include <functional>

Chapter 15: Multiple Inheritance

280

using namespace std;

int main() {

const int sz = 9; vector<string> vs(sz);

// Fill it with random number strings: generate(vs.begin(), vs.end(), NumStringGen()); copy(vs.begin(), vs.end(),

ostream_iterator<string>(cout, "\t")); cout << endl;

const char* vcp[sz]; transform(vs.begin(), vs.end(), vcp,

mem_fun_ref(&string::c_str)); vector<double> vd;

transform(vcp,vcp + sz,back_inserter(vd), std::atof);

copy(vd.begin(), vd.end(), ostream_iterator<double>(cout, "\t"));

cout << endl; } ///:~

The SGI extensions to the STL contain a number of additional function object templates that accomplish more detailed activities than the Standard C++ function object templates, including identity (returns its argument unchanged), project1st and project2nd (to take two arguments and return the first or second one, respectively), select1st and select2nd (to take a pair object and return the first or second element, respectively), and the “compose” function templates.

If you’re using the SGI extensions, you can make the above program denser using one of the two “compose” function templates. The first, compose1(f1, f2), takes the two function objects f1 and f2 as its arguments. It produces a function object that takes a single argument, passes it to f2, then takes the result of the call to f2 and passes it to f1. The result of f1 is returned. By using compose1( ), the process of converting the string objects to char*, then converting the char* to a floating-point number can be combined into a single operation, like this:

//: C05:MemFun4.cpp

// Using the SGI STL compose1 function #include "NumStringGen.h"

#include <algorithm> #include <vector> #include <string> #include <iostream> #include <functional> using namespace std;

Chapter 15: Multiple Inheritance

281

int main() {

const int sz = 9; vector<string> vs(sz);

// Fill it with random number strings: generate(vs.begin(), vs.end(), NumStringGen()); copy(vs.begin(), vs.end(),

ostream_iterator<string>(cout, "\t")); cout << endl;

vector<double> vd;

transform(vs.begin(), vs.end(), back_inserter(vd), compose1(ptr_fun(atof),

mem_fun_ref(&string::c_str))); copy(vd.begin(), vd.end(),

ostream_iterator<double>(cout, "\t")); cout << endl;

} ///:~

You can see there’s only a single call to transform( ) now, and no intermediate holder for the char pointers.

The second “compose” function is compose2( ), which takes three function objects as its arguments. The first function object is binary (it takes two arguments), and its arguments are the results of the second and third function objects, respectively. The function object that results from compose2( ) expects one argument, and it feeds that argument to the second and third function objects. Here is an example:

//: C05:Compose2.cpp

// Using the SGI STL compose2() function #include "copy_if.h"

#include <algorithm> #include <vector> #include <iostream> #include <functional> #include <cstdlib> #include <ctime> using namespace std;

int main() { srand(time(0)); vector<int> v(100);

generate(v.begin(), v.end(), rand); transform(v.begin(), v.end(), v.begin(),

bind2nd(divides<int>(), RAND_MAX/100)); vector<int> r;

copy_if(v.begin(), v.end(), back_inserter(r),

Chapter 15: Multiple Inheritance

282

compose2(logical_and<bool>(), bind2nd(greater_equal<int>(), 30), bind2nd(less_equal<int>(), 40)));

sort(r.begin(), r.end()); copy(r.begin(), r.end(),

ostream_iterator<int>(cout, " ")); cout << endl;

} ///:~

The vector<int> v is first filled with random numbers. To cut these down to size, the transform( ) algorithm is used to divide each value by RAND_MAX/100, which will force the values to be between 0 and 100 (making them more readable). The copy_if( ) algorithm defined later in this chapter is then used, along with a composed function object, to copy all the elements that are greater than or equal to 30 and less than or equal to 40 into the destination vector<int> r. Just to show how easy it is, r is sorted, and then displayed.

The arguments of compose2( ) say, in effect:

(x >= 30) && (x <= 40)

You could also take the function object that comes from a compose1( ) or compose2( ) call and pass it into another “compose” expression … but this could rapidly get very difficult to decipher.

Instead of all this composing and transforming, you can write your own function objects (without using the SGI extensions) as follows:

//: C05:NoCompose.cpp

// Writing out the function objects explicitly #include "copy_if.h"

#include <algorithm> #include <vector> #include <string> #include <iostream> #include <functional> #include <cstdlib> #include <ctime> using namespace std;

class Rgen { const int max;

public:

Rgen(int mx = 100) : max(RAND_MAX/mx) { srand(time(0));

}

int operator()() { return rand() / max; }

Chapter 15: Multiple Inheritance

283

};

class BoundTest { int top, bottom;

public:

BoundTest(int b, int t) : bottom(b), top(t) {} bool operator()(int arg) {

return (arg >= bottom) && (arg <= top);

}

};

int main() { vector<int> v(100);

generate(v.begin(), v.end(), Rgen()); vector<int> r;

copy_if(v.begin(), v.end(), back_inserter(r), BoundTest(30, 40));

sort(r.begin(), r.end()); copy(r.begin(), r.end(),

ostream_iterator<int>(cout, " ")); cout << endl;

} ///:~

There are a few more lines of code, but you can’t deny that it’s much clearer and easier to understand, and therefore to maintain.

We can thus observe two drawbacks to the SGI extensions to the STL. The first is simply that it’s an extension; yes, you can download and use them for free so the barriers to entry are low, but your company may be conservative and decide that if it’s not in Standard C++, they don’t want to use it. The second drawback is complexity. Once you get familiar and comfortable with the idea of composing complicated functions from simple ones you can visually parse complicated expressions and figure out what they mean. However, my guess is that most people will find anything more than what you can do with the Standard, non-extended STL function object notation to be overwhelming. At some point on the complexity curve you have to bite the bullet and write a regular class to produce your function object, and that point might as well be the point where you can’t use the Standard C++ STL. A stand-alone class for a function object is going to be much more readable and maintainable than a complicated function-composition expression (although my sense of adventure does lure me into wanting to experiment more with the SGI extensions…).

As a final note, you can’t compose generators; you can only create function objects whose operator( ) requires one or two arguments.

Chapter 15: Multiple Inheritance

284

Соседние файлы в предмете Численные методы
  • #
    08.05.20133.99 Mб22A.Menezes, P.van Oorschot,S.Vanstone - HANDBOOK OF APPLIED CRYPTOGRAPHY.djvu
  • #
  • #
    08.05.20135.91 Mб24B.Eckel - Thinking in Java, 3rd edition (beta).pdf
  • #
  • #
    08.05.20136.09 Mб17D.MacKay - Information Theory, Inference, and Learning Algorithms.djvu
  • #
    08.05.20133.85 Mб15DIGITAL Visual Fortran ver.5.0 - Programmers Guide to Fortran.djvu
  • #
    08.05.20131.84 Mб12E.A.Lee, P.Varaiya - Structure and Interpretation of Signals and Systems.djvu