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

Пример 11.22 реализует прямое решение, которое показывает, как следует писать простую обобщенную функцию в стиле STL. Для расчета расстояний между векторами я мог бы использовать функцию inner_product, однако я не стал использовать функтор, потому что это неоправданно усложнило бы решение. Пример 11.23 показывает, как можно рассчитывать расстояние между векторами, применяя функтор и функцию inner_product из заголовочного файла .

Пример 11.23. Расчет расстояния между векторами с использованием функции inner_product

#include

#include

#include

#include


using namespace std;


template

struct DiffSquared {

 Value_T operator()(Value_T x, Value_T y) const {

  return (x - y) * (x - y);

 }

};


template

double vectorDistance(Iter_T first, Iter_T last, Iter2_T first2) {

 double ret = inner_product(first, last, first2, 0.0L,

  plus(), DiffSquared());

 return ret > 0.0 ? sqrt(ret) : 0.0;

}


int main() {

 int v1[] = { 1, 5 };

 int v2[] = { 4, 9 };

 cout << "distance between vectors (1,5) and (4,9) is ";

 cout << vectorDistance(v1, v1 + 2, v2) << endl;

}

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

11.13. Реализация итератора с шагом

Проблема

Имеются смежные числовые ряды и требуется обеспечить доступ к каждому n-му элементу.

Решение

В примере 11.24 представлен заголовочный файл, реализующий класс итератора с шагом.

Пример 11.24. stride_iter.hpp

#ifndef STRIDE_ITER_HPP

#define STRIDE_ITER_HPP


#include

#include


template

class stride_iter {

public:


 // открытые имена, вводимые typedef

 typedef typename std::iterator_traits::value_type value_type;

 typedef typename std::iterator_traits::reference reference;

 typedef typename std::iterator_traits::difference_type

  difference_type;

 typedef typename std::iterator_traits::pointer pointer;

 typedef std::random_access_iterator_tag iterator_category;

 typedef stride_iter self;


 // конструкторы

 stride_iter() : m(NULL), step(0) {};

 stride_iter(const self& x) : m(x.m), step(x.step) {}

 stride_iter(Iter_T x, difference_type n) : m(x), step(n) {}


 // операторы

 self& operator++() { m += step; return *this; }

 self operator++(int) { self tmp = *this; m += step; return tmp; }

 self& operator+=(difference_type x) { m += x * step; return *this; }

 self& operator--() { m -= step; return *this; }

 self operator--(int) { self tmp = *this; m -= step; return trap; }

 self& operator--(difference type x) { m -= x + step; return *this; }

 reference operator[](difference_type n) { return m[n * step]; }

 reference operator*() { return *m; }


 // дружественные операторы

 friend bool operator==(const self& x, const self& y) {

  assert(x.step == y.step);

  return x.m == y.m;

 }

 friend bool operator!=(const self& x, const self& y) {

  assert(x.step == y.step);

  return x.m != y.m;

 }

 friend bool operator<(const self& x, const self& y) {

  assert(x.step == y.step);

  return x.m < y.m;

 }

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

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

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

Стивен Прата

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