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

Returns an iterator pointing to the first occurrence of the "smallest" value in the range (as explained below—there may be multiple occurrences of this value.) Returns last if the range is empty. The first version performs comparisons with operator<, and the value r returned is such that *e < *r is false for every element e in the range [first, r). The second version compares using binary_pred, and the value r returned is such that binary_pred (*e, *r) is false for every element e in the range [first, r).

ForwardIterator max_element(ForwardIterator first, ForwardIterator last); ForwardIterator max_element(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred);

Returns an iterator pointing to the first occurrence of the largest value in the range. (There may be multiple occurrences of the largest value.) Returns last if the range is empty. The first version performs comparisons with operator<, and the value r returned is such that *r < *e is false for every element e in the range [first, r). The second version compares using binary_pred, and the value r returned is such that binary_pred (*r, *e) is false for every element e in the range [first, r).

void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value); void replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value); OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value); OutputIterator replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value);

Each of the "replace" forms moves through the range [first, last), finding values that match a criterion and replacing them with new_value. Both replace( ) and replace_copy( ) simply look for old_value to replace; replace_if( ) and replace_copy_if( ) look for values that satisfy the predicate pred. The "copy" versions of the functions do not modify the original range but instead make a copy with the replacements into result (incrementing result after each assignment).

<p>Example</p>

To provide easy viewing of the results, this example manipulates vectors of int. Again, not every possible version of each algorithm is shown. (Some that should be obvious have been omitted.)

//: C06:SearchReplace.cpp

// The STL search and replace algorithms

#include

#include

#include

#include "PrintSequence.h"

using namespace std;

struct PlusOne {

  bool operator()(int i, int j) {

    return j == i + 1;

  }

};

class MulMoreThan {

  int value;

public:

  MulMoreThan(int val) : value(val) {}

  bool operator()(int v, int m) {

    return v * m > value;

  }

};

int main() {

  int a[] = { 1, 2, 3, 4, 5, 6, 6, 7, 7, 7,

    8, 8, 8, 8, 11, 11, 11, 11, 11 };

  const int asz = sizeof a / sizeof *a;

  vector v(a, a + asz);

  print(v.begin(), v.end(), "v", " ");

  vector::iterator it =

    find(v.begin(), v.end(), 4);

  cout << "find: " << *it << endl;

  it = find_if(v.begin(), v.end(),

    bind2nd(greater(), 8));

  cout << "find_if: " << *it << endl;

  it = adjacent_find(v.begin(), v.end());

  while(it != v.end()) {

    cout << "adjacent_find: " << *it

      << ", " << *(it + 1) << endl;

    it = adjacent_find(it + 1, v.end());

  }

  it = adjacent_find(v.begin(), v.end(),

    PlusOne());

  while(it != v.end()) {

    cout << "adjacent_find PlusOne: " << *it

      << ", " << *(it + 1) << endl;

    it = adjacent_find(it + 1, v.end(),

      PlusOne());

  }

  int b[] = { 8, 11 };

  const int bsz = sizeof b / sizeof *b;

  print(b, b + bsz, "b", " ");

  it = find_first_of(v.begin(), v.end(),

    b, b + bsz);

  print(it, it + bsz, "find_first_of", " ");

  it = find_first_of(v.begin(), v.end(),

    b, b + bsz, PlusOne());

  print(it,it + bsz,"find_first_of PlusOne"," ");

  it = search(v.begin(), v.end(), b, b + bsz);

  print(it, it + bsz, "search", " ");

  int c[] = { 5, 6, 7 };

  const int csz = sizeof c / sizeof *c;

  print(c, c + csz, "c", " ");

  it = search(v.begin(), v.end(),

    c, c + csz, PlusOne());

  print(it, it + csz,"search PlusOne", " ");

  int d[] = { 11, 11, 11 };

  const int dsz = sizeof d / sizeof *d;

  print(d, d + dsz, "d", " ");

  it = find_end(v.begin(), v.end(), d, d + dsz);

  print(it, v.end(),"find_end", " ");

  int e[] = { 9, 9 };

  print(e, e + 2, "e", " ");

  it = find_end(v.begin(), v.end(),

    e, e + 2, PlusOne());

  print(it, v.end(),"find_end PlusOne"," ");

  it = search_n(v.begin(), v.end(), 3, 7);

  print(it, it + 3, "search_n 3, 7", " ");

  it = search_n(v.begin(), v.end(),

    6, 15, MulMoreThan(100));

  print(it, it + 6,

    "search_n 6, 15, MulMoreThan(100)", " ");

  cout << "min_element: " <<

    *min_element(v.begin(), v.end()) << endl;

  cout << "max_element: " <<

    *max_element(v.begin(), v.end()) << endl;

  vector v2;

  replace_copy(v.begin(), v.end(),

    back_inserter(v2), 8, 47);

  print(v2.begin(), v2.end(), "replace_copy 8 -> 47", " ");

  replace_if(v.begin(), v.end(),

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

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

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

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

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

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

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

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

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