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

  Compare comp;

public:

  // Don't need to call make_heap(); it's empty:

  PQV(Compare cmp = Compare()) : comp(cmp) {}

  void push(const T& x) {

    // Put it at the end:

    v.push_back(x);

    // Re-adjust the heap:

    push_heap(v.begin(), v.end(), comp);

  }

  void pop() {

    // Move the top element to the last position:

    pop_heap(v.begin(), v.end(), comp);

    // Remove that element:

    v.pop_back();

  }

  const T& top() { return v.front(); }

  bool empty() const { return v.empty(); }

  int size() const { return v.size(); }

  typedef vector TVec;

  TVec vector() {

    TVec r(v.begin(), v.end());

    // It’s already a heap

    sort_heap(r.begin(), r.end(), comp);

    // Put it into priority-queue order:

    reverse(r.begin(), r.end());

    return r;

  }

};

int main() {

  PQV > pqi;

  srand(time(0));

  for(int i = 0; i < 100; i++)

    pqi.push(rand() % 25);

  const vector& v = pqi.vector();

  copy(v.begin(), v.end(),

    ostream_iterator(cout, " "));

  cout << "\n-----------\n";

  while(!pqi.empty()) {

    cout << pqi.top() << ' ';

    pqi.pop();

  }

} ///:~

The PQV class template follows the same form as the STL’s priority_queue, but has the additional member vector( ), which creates a new vector that’s a copy of the one in PQV (which means that it’s already a heap). It then sorts that copy (leaving PQV’s vector untouched), and reverses the order so that traversing the new vector produces the same effect as popping the elements from the priority queue.

You may observe that the approach of deriving from priority_queue used in PriorityQueue4.cpp could be used with the above technique to produce more succinct code:

//: C07:PriorityQueue8.cpp

// A more compact version of PriorityQueue7.cpp

#include

#include

#include

#include

#include

#include

using namespace std;

template

class PQV : public priority_queue {

public:

  typedef vector TVec;

  TVec vector() {

    TVec r(c.begin(), c.end());

    // c is already a heap

    sort_heap(r.begin(), r.end(), comp);

    // Put it into priority-queue order:

    reverse(r.begin(), r.end());

    return r;

  }

};

int main() {

  PQV pqi;

  srand(time(0));

  for(int i = 0; i < 100; i++)

    pqi.push(rand() % 25);

  const vector& v = pqi.vector();

  copy(v.begin(), v.end(),

    ostream_iterator(cout, " "));

  cout << "\n-----------\n";

  while(!pqi.empty()) {

    cout << pqi.top() << ' ';

    pqi.pop();

  }

} ///:~

The brevity of this solution makes it the simplest and most desirable, plus it’s guaranteed that the user will not have a vector in the unsorted state. The only potential problem is that the vector( ) member function returns the vector by value, which might cause some overhead issues with complex values of the parameter type T.

<p>Holding bits</p>

Because C was a language that purported to be "close to the hardware," many have found it dismaying that there was no native binary representation for numbers. Decimal, of course, and hexadecimal (tolerable only because it’s easier to group the bits in your mind), but octal? Ugh. Whenever you read specs for chips you’re trying to program, they don’t describe the chip registers in octal or even hexadecimal—they use binary. And yet C won’t let you say 0b0101101, which is the obvious solution for a language close to the hardware.

Although there’s still no native binary representation in C++, things have improved with the addition of two classes: bitset and vector, both of which are designed to manipulate a group of on-off values.[100] The primary differences between these types are:

1.Each bitset holds a fixed number of bits. You establish the quantity of bits in the bitset template argument. The vector can, like a regular vector, expand dynamically to hold any number of bool values.

2.The bitset template is explicitly designed for performance when manipulating bits, and is not a "regular" STL container. As such, it has no iterators. The number of bits, being a template parameter, is known at compile time and allows the underlying integral array to be stored on the runtime stack. The vector container, on the other hand, is a specialization of a vector and so has all the operations of a normal vector—the specialization is just designed to be space efficient for bool.

There is no trivial conversion between a bitset and a vector, which implies that the two are for very different purposes. Furthermore, neither is a traditional "STL container." The bitset template class has an interface for bit-level operations and in no way resembles the STL containers we’ve discussed up to this point. The vector specialization of vector is similar to an STL-like container, but it differs as discussed below.

<p>bitset<n></n></p>

The template for bitset accepts an unsigned integral template argument that is the number of bits to represent. Thus, bitset<10> is a different type than bitset<20>, and you cannot perform comparisons, assignments, and so on between the two.

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

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

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

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

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

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

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

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

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