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

The list has some special built-in operations to make the best use of the structure of the list. You’ve already seen reverse( ) and sort( ), and here are some of the others in use:

//: C07:ListSpecialFunctions.cpp

#include

#include

#include

#include

#include "Noisy.h"

using namespace std;

ostream_iterator out(cout, " ");

void print(list& ln, char* comment = "") {

  cout << "\n" << comment << ":\n";

  copy(ln.begin(), ln.end(), out);

  cout << endl;

}

int main() {

  typedef list LN;

  LN l1, l2, l3, l4;

  generate_n(back_inserter(l1), 6, NoisyGen());

  generate_n(back_inserter(l2), 6, NoisyGen());

  generate_n(back_inserter(l3), 6, NoisyGen());

  generate_n(back_inserter(l4), 6, NoisyGen());

  print(l1, "l1"); print(l2, "l2");

  print(l3, "l3"); print(l4, "l4");

  LN::iterator it1 = l1.begin();

  it1++; it1++; it1++;

  l1.splice(it1, l2);

  print(l1, "l1 after splice(it1, l2)");

  print(l2, "l2 after splice(it1, l2)");

  LN::iterator it2 = l3.begin();

  it2++; it2++; it2++;

  l1.splice(it1, l3, it2);

  print(l1, "l1 after splice(it1, l3, it2)");

  LN::iterator it3 = l4.begin(), it4 = l4.end();

  it3++; it4--;

  l1.splice(it1, l4, it3, it4);

  print(l1, "l1 after splice(it1,l4,it3,it4)");

  Noisy n;

  LN l5(3, n);

  generate_n(back_inserter(l5), 4, NoisyGen());

  l5.push_back(n);

  print(l5, "l5 before remove()");

  l5.remove(l5.front());

  print(l5, "l5 after remove()");

  l1.sort(); l5.sort();

  l5.merge(l1);

  print(l5, "l5 after l5.merge(l1)");

  cout << "\n Cleanup" << endl;

} ///:~

The print( ) function displays results. After filling four lists with Noisy objects, one list is spliced into another in three ways. In the first, the entire list l2 is spliced into l1 at the iterator it1. Notice that after the splice, l2 is empty—splicing means removing the elements from the source list. The second splice inserts elements from l3 starting at it2 into l1 starting at it1. The third splice starts at it1 and uses elements from l4 starting at it3 and ending at it4 (the seemingly redundant mention of the source list is because the elements must be erased from the source list as part of the transfer to the destination list).

The output from the code that demonstrates remove( ) shows that the list does not have to be sorted in order for all the elements of a particular value to be removed.

Finally, if you merge( ) one list with another, the merge only works sensibly if the lists have been sorted. What you end up with in that case is a sorted list containing all the elements from both lists (the source list is erased—that is, the elements are moved to the destination list).

A unique( ) member function removes all duplicates, but only if you sort the list first:

//: C07:UniqueList.cpp

// Testing list's unique() function

#include

#include

#include

using namespace std;

int a[] = { 1, 3, 1, 4, 1, 5, 1, 6, 1 };

const int asz = sizeof a / sizeof *a;

int main() {

  // For output:

  ostream_iterator out(cout, " ");

  list li(a, a + asz);

  li.unique();

  // Oops! No duplicates removed:

  copy(li.begin(), li.end(), out);

  cout << endl;

  // Must sort it first:

  li.sort();

  copy(li.begin(), li.end(), out);

  cout << endl;

  // Now unique() will have an effect:

  li.unique();

  copy(li.begin(), li.end(), out);

  cout << endl;

} ///:~

The list constructor used here takes the starting and past-the-end iterator from another container and copies all the elements from that container into itself. (A similar constructor is available for all the containers.) Here, the "container" is just an array, and the "iterators" are pointers into that array, but because of the design of the STL, it works with arrays just as easily as any other container.

The unique( ) function will remove only adjacent duplicate elements, and thus sorting is necessary before calling unique( ).

Four additional list member functions are not demonstrated here: a remove_if( ) that takes a predicate, which decides whether an object should be removed; a unique( ) that takes a binary predicate to perform uniqueness comparisons; a merge( ) that takes an additional argument which performs comparisons; and a sort( ) that takes a comparator (to provide a comparison or override the existing one).

<p>list vs. set</p>

Looking at the previous example, you might note that if you want a sorted list with no duplicates, a set can give you that, right? It’s interesting to compare the performance of the two containers:

//: C07:ListVsSet.cpp

// Comparing list and set performance

#include

#include

#include

#include

#include

#include

using namespace std;

class Obj {

  int a[20]; // To take up extra space

  int val;

public:

  Obj() : val(rand() % 500) {}

  friend bool

  operator<(const Obj& a, const Obj& b) {

    return a.val < b.val;

  }

  friend bool

  operator==(const Obj& a, const Obj& b) {

    return a.val == b.val;

  }

  friend ostream&

  operator<<(ostream& os, const Obj& a) {

    return os << a.val;

  }

};

template

void print(Container& c) {

  typename Container::iterator it;

  for(it = c.begin(); it != c.end(); it++)

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

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

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

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

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

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

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

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

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