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

You can also use the resize( ) member function that belongs to all standard sequences (more on this in the next chapter).

The return value of remove( ) is the new_last iterator, so erase( ) deletes all the removed elements from c.

The iterators in [new_last, last) are dereferenceable, but the element values are unspecified and should not be used.

ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value); ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate pred); OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value); OutputIterator remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred);

Each of the "remove" forms moves through the range [first, last), finding values that match a removal criterion and copying the unremoved elements over the removed elements (thus effectively removing them). The original order of the unremoved elements is maintained. The return value is an iterator pointing past the end of the range that contains none of the removed elements. The values that this iterator points to are unspecified.

The "if" versions pass each element to pred( ) to determine whether it should be removed. (If pred( ) returns true, the element is removed.) The "copy" versions do not modify the original sequence, but instead copy the unremoved values into a range beginning at result and return an iterator indicating the past-the-end value of this new range.

ForwardIterator unique(ForwardIterator first, ForwardIterator last); ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred); OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result); OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result,  BinaryPredicate binary_pred);

Each of the "unique" functions moves through the range [first, last), finding adjacent values that are equivalent (that is, duplicates) and "removing" the duplicate elements by copying over them. The original order of the unremoved elements is maintained. The return value is an iterator pointing past the end of the range that has the adjacent duplicates removed.

Because only duplicates that are adjacent are removed, it’s likely that you’ll want to call sort( ) before calling a "unique" algorithm, since that will guarantee that all the duplicates are removed.

For each iterator value i in the input range, the versions containing binary_pred call:.

binary_pred(*i, *(i-1));

and if the result is true, *i is considered a duplicate.

The "copy" versions do not modify the original sequence, but instead copy the unremoved values into a range beginning at result and return an iterator indicating the past-the-end value of this new range.

<p>Example</p>

This example gives a visual demonstration of the way the "remove" and "unique" functions work.

//: C06:Removing.cpp

// The removing algorithms

#include

#include

#include

#include "Generators.h"

#include "PrintSequence.h"

using namespace std;

struct IsUpper {

  bool operator()(char c) {

    return isupper(c);

  }

};

int main() {

  string v;

  v.resize(25);

  generate(v.begin(), v.end(), CharGen());

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

  // Create a set of the characters in v:

  string us(v.begin(), v.end());

  sort(us.begin(), us.end());

  string::iterator it = us.begin(), cit = v.end(),

    uend = unique(us.begin(), us.end());

  // Step through and remove everything:

  while(it != uend) {

    cit = remove(v.begin(), cit, *it);

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

    print(v.begin(), cit, "Pseudo v ", " ");

    cout << "Removed element:\t" << *it

         << "\nPsuedo Last Element:\t"

         << *cit << endl << endl;

    it++;

  }

  generate(v.begin(), v.end(), CharGen());

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

  cit = remove_if(v.begin(), v.end(), IsUpper());

  print(v.begin(), cit, "v after remove_if IsUpper", " ");

  // Copying versions are not shown for remove

  // and remove_if.

  sort(v.begin(), cit);

  print(v.begin(), cit, "sorted", " ");

  string v2;

  v2.resize(cit - v.begin());

  unique_copy(v.begin(), cit, v2.begin());

  print(v2.begin(), v2.end(), "unique_copy", " ");

  // Same behavior:

  cit = unique(v.begin(), cit, equal_to());

  print(v.begin(), cit, "unique equal_to", " ");

} ///:~

The string v, which is a container of characters, as you know, is filled with randomly generated characters. Each character is used in a remove statement, but the entire string v is printed out each time so you can see what happens to the rest of the range, after the resulting endpoint (which is stored in cit).

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

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

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

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

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

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

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

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

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