Читаем Thinking In C++. Volume 2: Practical Programming полностью

template

  typename OutputIter, typename UnaryPred>

OutputIter copy_if(ForwardIter begin, ForwardIter end,

  OutputIter dest, UnaryPred f) {

  while(begin != end) {

    if(f(*begin))

      *dest++ = *begin;

    ++begin;

  }

  return dest;

}

#endif // COPY_IF_H ///:~

<p>Summary</p>

The goal of this chapter was to give you a practical understanding of the algorithms in the Standard Template Library. That is, to make you aware of and comfortable enough with the STL that you begin to use it on a regular basis (or, at least, to think of using it so you can come back here and hunt for the appropriate solution). It is powerful not only because it’s a reasonably complete library of tools, but also because it provides a vocabulary for thinking about problem solutions and because it is a framework for creating additional tools.

Although this chapter did show some examples of creating your own tools, we did not go into the full depth of the theory of the STL that is necessary to completely understand all the STL nooks and crannies to allow you to create tools more sophisticated than those shown here. This was in part because of space limitations, but mostly because it is beyond the charter of this book; our goal here is to give you practical understanding that will affect your day-to-day programming skills.

A number of books are dedicated solely to the STL (these are listed in the appendices), but we especially recommend Matthew H. Austern’s Generic Programming and the STL (Addison-Wesley, 1999) and Scott Meyers’s Effective STL (Addison-Wesley, 2002).

<p>Exercises</p>

             4.             Create a generator that returns the current value of clock( ) (in ). Create a list, and fill it with your generator using generate_n( ). Remove any duplicates in the list and print it to cout using copy( ).

             4.             Using transform( ) and toupper( ) (in ), write a single function call that will convert a string to all uppercase letters.

             5.             Create a Sum function object template that will accumulate all the values in a range when used with for_each( ).

             6.             Write an anagram generator that takes a word as a command-line argument and produces all possible permutations of the letters.

             7.             Write a "sentence anagram generator" that takes a sentence as a command-line argument and produces all possible permutations of the words in the sentence. (It leaves the words alone and just moves them around.)

             8.             Create a class hierarchy with a base class B and a derived class D. Put a virtual member function void f( ) in B such that it will print a message indicating that B’s f( ) was called, and redefine this function for D to print a different message. Create a vector, and fill it with B and D objects. Use for_each( ) to call f( ) for each of the objects in your vector.

             9.             Modify FunctionObjects.cpp so that it uses float instead of int.

        10.             Modify FunctionObjects.cpp so that it templatizes the main body of tests so you can choose which type you’re going to test. (You’ll have to pull most of main( ) out into a separate template function.)

         11.             Write a program that takes an integer as a command line argument and finds all of its factors.

         12.             Write a program that takes as a command-line argument the name of a text file. Open this file and read it a word at a time (hint: use >>). Store each word into a vector. Force all the words to lowercase, sort them, remove all the duplicates, and print the results.

         13.             Write a program that finds all the words that are in common between two input files, using set_intersection( ). Change it to show the words that are not in common, using set_symmetric_difference( ).

         14.             Create a program that, given an integer on the command line, creates a "factorial table" of all the factorials up to and including the number on the command line. To do this, write a generator to fill a vector, and then use partial_sum( ) with a standard function object.

         15.             Modify CalcInventory.cpp so that it will find all the objects that have a quantity that’s less than a certain amount. Provide this amount as a command-line argument, and use copy_if( ) and bind2nd( ) to create the collection of values less than the target value.

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных