Читаем C++. Сборник рецептов полностью

В примере 11.35 с помощью typedef я определил тип Polar как специализацию шаблона BasicPolar. Так удобно определять используемый по умолчанию тип, однако вы можете при необходимости специализировать шаблон BasicPolar другим числовым типом. Такой подход используется в стандартной библиотеке в отношении классе string, который является специализацией шаблона basic_string.

11.19. Выполнение операций с битовыми наборами

Проблема

Требуется реализовать основные арифметические операции и операции сравнения для набора бит, рассматривая его как двоичное представление целого числа без знака.

Решение

Программный код примера 11.36 содержит функции, которые позволяют выполнять арифметические операции и операции сравнения с шаблоном класса bitset из заголовочного файла , рассматривая его как целый тип без знака.

Пример 11.36. bitset_arithmetic.hpp

#include

#include


bool fullAdder(bool b1, bool b2, bool& carry) {

 bool sum = (b1 ^ b2) ^ carry;

 carry = (b1 && b2) || (b1 && carry) || (b2 && carry);

 return sum;

}


bool fullSubtractor(bool b1, bool b2, bool& borrow) {

 bool diff;

 if (borrow) {

  diff = !(b1 ^ b2);

  borrow = !b1 || (b1 && b2);

 } else {

  diff = b1 ^ b2;

  borrow = !b1 && b2;

 }

 return diff;

}


template

bool bitsetLtEq(const std::bitset& x, const std::bitset& y) {

 for (int i=N-1; i >= 0; i--) {

  if (x[i] && !y[i]) return false;

  if (!x[i] && y[i]) return true;

 }

 return true;

}


template

bool bitsetLt(const std::bitset& x, const std::bitset& y) {

 for (int i=N-1; i >= 0, i--) {

  if (x[i] && !y[i]) return false;

  if (!x[i] && y[i]) return true;

 }

 return false;

}


template

bool bitsetGtEq(const std::bitset& x, const std::bitset& y) {

 for (int i=N-1; i >= 0; i--) {

  if (x[i] && !y[i]) return true;

  if (!x[i] && y[i]) return false;

 }

 return true;

}


template

bool bitsetGt(const std::bitset& x, const std::bitset& y) {

 for (int i=N-1; i >= 0; i--) {

  if (x[i] && !y[i]) return true;

  if (!x[i] && y[i]) return false;

 }

 return false;

}


template

void bitsetAdd(std::bitset& x, const std::bitset& y) {

 bool carry = false;

 for (int i = 0; i < N; i++) {

  x[i] = fullAdder(x[i], y[x], carry);

 }

}


template

void bitsetSubtract(std::bitset& x, const std::bitset& y) {

 bool borrow = false;

 for (int i = 0; i < N; i++) {

  if (borrow) {

   if (x[i]) {

    x[i] = y[i];

    borrow = y[i];

   } else {

    x[i] = !y[i];

    borrow = true;

   }

  } else {

   if (x[i]) {

    x[i] = !y[i];

    borrow = false;

   } else {

    x[i] = y[i];

    borrow = y[i];

   }

  }

 }

}


template

void bitsetMultiply(std::bitset& x, const std::bitset& y) {

 std::bitset tmp = x;

 x.reset();

 // мы хотим минимизировать количество операций сдвига и сложения

 if (tmp.count() < y.count()) {

  for (int i=0; i < N; i++) if (tmp[i]) bitsetAdd(x, у << i);

 } else {

  for (int i=0; i < N; i++) if (y[i]) bitsetAdd(x, tmp << i);

 }

}


template

void bitsetDivide(std::bitset x, std::bitset y,

 std::bitset& q, std::bitset& r) {

 if (y.none()) {

  throw std::domain_error("division by zero undefined");

 }

 q.reset();

 r.reset();

 if (x.none()) {

  return;

 }

 if (x == y) {

  q[0] = 1;

  return;

 }

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

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

1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

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

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

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

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

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