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

 friend difference_type operator-(self x, self y) {

  return (x.m - y.m) / Step_N;

 }


 friend self operator+(self x, difference_type y) { return x += y * Step_N; }

 friend self operator+(difference_type x, self y) { return y += x * Step_N; }

private:

 Iter_T m;

};


#endif

Пример 11.27 показывает, как можно использовать итератор kstride_iter.

Пример 11.27. Применение итератора kstride_iter

#include "kstride_iter.hpp"

#include

#include

#include


using namespace std;


int main() {

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

 kstride_iter first(a);

 kstride_iter last(a + 8);

 copy(first, last, ostream_iterator(cout, "\n"));

}

11.14. Реализация динамической матрицы

Проблема

Требуется реализовать числовые матрицы, размерности которых (количество строк и столбцов) неизвестны на этапе компиляции.

Решение

В примере 11.28 показана универсальная и эффективная реализация класса динамической матрицы, использующая итератор с шагом из рецепта 11.12 и valarray.

Пример 11.28. matrix.hpp

#ifndef MATRIX_HPP

#define MATRIX_HPP


#include "stride_iter.hpp" // см. рецепт 11.12

#include

#include

#include


template

class matrix {

public:

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

 typedef Value_T value_type;

 typedef matrix self;

 typedef value_type* iterator;

 typedef const value_type* const_iterator;

 typedef Value_T* row_type;

 typedef stride_iter col_type;

 typedef const value_type* const_row_type;

 typedef stride_iter const_col_type;


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

 matrix() : nrows(0), ncols(0), m() {}

 matrix(int r, int c) : nrows(r), ncols(c), m(r * с) {}

 matrix(const self& x) : m(x.m), nrows(x.nrows), ncols(x.ncols) {}

 template

 explicit matrix(const valarray& x)

  : m(x.size() + 1), nrows(x.size()), ncols(1) {

  for (int i=0; i

 }

 // позволить конструирование из матриц других типов

 template explicit matrix(const matrix& x)

  : m(x.size() + 1), nrows(x.nrows), ncols(x.ncols) {

  copy(x.begin(), x.end(), m.begin());

 }


// открытые функции

 int rows() const { return nrows; }

 int cols() const { return ncols; }

 int size() const { return nrows * ncols; }


 // доступ к элементам

 row_type row begin(int n) { return &m[n * cols()]; }

 row_type row_end(int n) { return row_begin() + cols(); }

 col_type col_begin(int n) { return col_type(&m[n], cols()); }

 col_type col_end(int n) { return col_begin(n) + cols(); }

 const_row_type row_begin(int n) const { return &m[n * cols()]; }

 const_row_type row_end(int n) const { return row_begin() + cols(); }

 const_col_type col_begin(int n) const { return col_type(&m[n], cols()); }

 const_col_type col_end(int n) const { return col_begin() + cols(); }

 iterator begin() { return &m[0]; }

 iterator end() { return begin() + size(); }

 const_iterator begin() const { return &m[0]; }

 const_iterator end() const { return begin() + size(); }


 // операторы

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

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

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

Стивен Прата

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