Консультация № 175598
25.12.2009, 05:44
35.00 руб.
0 5 1
Здравствуйте уважаемые эксперты!
Помогите пожалуйста: необходимо разработать подпрограмму, возвращающую количество объектов, находящихся в области видимости.
Заранее благодарен.

Приложение:
#include <iostream>
#include <memory>
#include <cstring>
#include <stdexcept>

using std::cout;
using std::cin;
using std::endl;
using std::auto_ptr;
using std::ostream;
using std::out_of_range;
// Шаблонный класс-массив
template<class M>
class mint
{
static int count; //количество объектов
public:
// Используемые типы
typedef int index_type;
typedef unsigned int size_type;
// Конструкторы
explicit mint(size_type length = 10);
mint(index_type lo, size_type length);
mint(const mint<M>& arr);
// Оператор присваивания
const mint<M> & operator=(const mint<M>& arr);
// Возвращает минимальный индекс
index_type lo() const;
// Возвращает максимальный индекс
index_type hi() const;
// Возвращает размер
size_type length() const;
// Индексаторы
M & operator[](index_type index);
const M & operator[](index_type index) const;
private:
// Мин. индекс
index_type _lo;
// Длина
size_type _length;
// Данные
auto_ptr<M> _data;
template<class My> friend mint<My> operator*(const mint<My>& arr, My val);
template<class My> friend mint<My> operator+(const mint<My>& arr, My val);
};
// Требуемые операторы
template<class My> mint<My> operator*(My val, const mint<My>& arr);
template<class My> mint<My> operator+(My val, const mint<My>& arr);
template<class M> ostream & operator<<(ostream& stream, const mint<M>& arr);

template <class M> int mint<M>::count = 0;

// Оператор вывода для массива
template<class M>
ostream & operator<<(ostream& stream, const mint<M>& arr)
{
for (typename mint<M>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
stream << arr[i] << ' ';
}
return stream;
}
template<class M>
mint<M>::mint(typename mint<M>::size_type length)
: _lo(1)
, _length(length)
, _data(new M[length]())
{
}
template<class M>
mint<M>::mint(index_type lo, size_type length)
: _lo(lo)
, _length(length)
, _data(new M[length]())
{
}
// Оператор копирования
template<class M>
mint<M>::mint(const mint<M>& arr)
: _lo(arr._lo) // Копируем нижний индекс
, _length(arr._length) // Копируем длину массива
, _data(new M[arr._length]()) // Создадим массив с такой же длиной

{
// Копируем данные
memcpy(_data.get(), arr._data.get(), _length * sizeof (M));
++count;
}
template<class M>
const mint<M>& mint<M>::operator=(const mint<M>& arr)
{
if (this != &arr)
{
_data.reset(new M[_length = arr._length]());
_lo = arr._lo;
memcpy(_data.get(), arr._data.get(), _length * sizeof (M));
}
return *this;
}
template<class M>
typename mint<M>::index_type mint<M>::lo() const
{
return _lo;
}
template<class M>
typename mint<M>::index_type mint<M>::hi() const
{
return _lo - 1 + _length;
}
template<class M>
typename mint<M>::size_type mint<M>::length() const
{
return _length;
}
template<class M>
M& mint<M>::operator[](index_type index)
{
if ((index -= _lo) < _length)
{
return *(_data.get() + index);
}
else out_of_range("Index out of bounds");
}
template<class M>
const M& mint<M>::operator[](index_type index) const
{
if ((index -= _lo) < _length)
{
return *(_data.get() + index);
}
else out_of_range("Index out of bounds");
}
// Оператор умножения массива на значение
template<class My>
mint<My> operator*(const mint<My>& arr, My val)
{
// Копируем массив в result
mint<My> result = arr;
// Получим указатель на начало данных
My* cur = result._data.get();
// Указатель на конец данных
const My * const end = cur + arr._length;
// Перебираем данные
while (cur != end)
{
// Умножаем каждый элемент и сдвигаем указатель на следующий
*cur++ *= val;
}
return result;
}
template<class My>
mint<My> operator*(My val, const mint<My>& arr)
{
return arr*val;
}
// Оператор прибавления к массиву значения
template<class My>
mint<My> operator+(const mint<My>& arr, My val)
{
mint<My> result = arr;
My* cur = result._data.get();
const My * const end = cur + arr._length;
while (cur != end)
{
*cur++ += val;
}
return result;
}
template<class My>
mint<My> operator+(My val, const mint<My>& arr)
{
return arr + val;
}
int main()
{
// Создаем массив из 20 элементов с первым индексом -10
mint<int> arr(-10, 20);

for (mint<int>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
arr[i] = i;
}
cout << "lo:" << arr.lo()<<endl;
cout << "hi:" << arr.hi()<<endl;
cout << "length:" << arr.length()<<endl;
cout << "Massiv:" << arr<<endl;
cout << "Massiv*10:" << 10 * arr;
cout << "Massiv+10:" << 10 + arr<<endl;
return 0;
}

Обсуждение

Неизвестный
25.12.2009, 10:07
общий
Мих@ил:
Каких объектов? Тем более, как Вы предполагаете решать какие из них в области видимости, а какие нет?
Неизвестный
25.12.2009, 11:29
общий
Мих@ил:
Т.е. Вам надо сделать счетчик объектов типа массив? Но настораживает фраза "находящихся в области видимости". Т.к. он будет считать общее количество объектов, а не находящихся в области видимости.
Неизвестный
25.12.2009, 11:45
общий
это ответ
Здравствуйте, Мих@ил.
Цитата: 300522
Объектом насколько я понял будет массив (arr), находящихся в области видимости - количество этих массивов (предполагается что созданных массивов может быть несколько).

Код:
#include <iostream>
#include <cstring>
#include <stdexcept>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::out_of_range;

// Шаблонный класс-массив
template<class T>
class array
{
public:
// Используемые типы
typedef int index_type;
typedef unsigned int size_type;
// Конструкторы
explicit array(size_type length = 10);
array(index_type lo, size_type length);
array(const array<T>& arr);
virtual ~array();
// Оператор присваивания
const array<T> & operator=(const array<T>& arr);
// Возвращает минимальный индекс
index_type lo() const;
// Возвращает максимальный индекс
index_type hi() const;
// Возвращает размер
size_type length() const;
// Индексаторы
T & operator[](index_type index);
const T & operator[](index_type index) const;
static size_t count();
private:
static size_t _count;
// Мин. индекс
index_type _lo;
// Длина
size_type _length;
// Данные
T* _data;
template<class Ty> friend array<Ty> operator*(const array<Ty>& arr, Ty val);
template<class Ty> friend array<Ty> operator+(const array<Ty>& arr, Ty val);
};

template<class T> size_t array<T>::_count=0;

// Требуемые операторы
template<class Ty> array<Ty> operator*(const array<Ty>& arr, Ty val);
template<class Ty> array<Ty> operator*(Ty val, const array<Ty>& arr);
template<class Ty> array<Ty> operator+(const array<Ty>& arr, Ty val);
template<class Ty> array<Ty> operator+(Ty val, const array<Ty>& arr);

template<class T> ostream& operator<<(ostream& stream, const array<T>& arr);

typedef array<int> int_array;

int main()
{
// Создаем массив из 20 элементов с первым индексом -10
int_array arr(-10, 20);
for (array<int>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
arr[i] = i;
}
cout << "lo:" << arr.lo() << endl
<< "hi:" << arr.hi() << endl
<< "length:" << arr.length() << endl;
cout << "Array:" << arr << endl;
cout << "Array*10:" << 10 * arr << endl;
cout << "Array+10:" << 10 + arr << endl;
cout<<"Count:"<<int_array::count()<<endl;
{
int_array b(arr);
cout<<"Count:"<<int_array::count()<<endl;
}
cout<<"Count:"<<int_array::count()<<endl;

return 0;
}

// Оператор вывода для массива
template<class T>
ostream& operator<<(ostream& stream, const array<T>& arr)
{
for (typename array<T>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
stream << arr[i] << ' ';
}
return stream;
}

template<class T>
array<T>::array(typename array<T>::size_type length)
: _lo(1)
, _length(length)
, _data(new T[length]())
{
++_count;
}

template<class T>
array<T>::array(index_type lo, size_type length)
: _lo(lo)
, _length(length)
, _data(new T[length]())
{
++_count;
}

// Оператор копирования
template<class T>
array<T>::array(const array<T>& arr)
: _lo(arr._lo) // Копируем нижний индекс
, _length(arr._length) // Копируем длину массива
, _data(new T[arr._length]()) // Создадим массив с такой же длиной
{
// Копируем данные
memcpy(_data, arr._data, _length * sizeof (T));
++_count;
}

template<class T>
array<T>::~array()
{
if(_data)
{
delete[] _data;
_data=0;
--_count;
}
}

template<class T>
const array<T>& array<T>::operator=(const array<T>& arr)
{
if (this != &arr)
{
delete[] _data;
_data=new T[_length = arr._length]();
_lo = arr._lo;
memcpy(_data, arr._data, _length * sizeof (T));
++_count;
}
return *this;
}

template<class T>
typename array<T>::index_type array<T>::lo() const
{
return _lo;
}

template<class T>
typename array<T>::index_type array<T>::hi() const
{
return _lo - 1 + _length;
}

template<class T>
typename array<T>::size_type array<T>::length() const
{
return _length;
}

template<class T>
T& array<T>::operator[](index_type index)
{
if ((index -= _lo) < _length)
{
return *(_data + index);
}
else throw out_of_range("Index out of bounds");
}

template<class T>
const T& array<T>::operator[](index_type index) const
{
if ((index -= _lo) < _length)
{
return *(_data + index);
}
else throw out_of_range("Index out of bounds");
}

template<class T>
size_t array<T>::count()
{
return _count;
}

// Оператор умножения массива на значение
template<class Ty>
array<Ty> operator*(const array<Ty>& arr, Ty val)
{

// Копируем массив в result
array<Ty> result = arr;
// Получим указатель на начало данных
Ty* cur = result._data;
// Указатель на конец данных
const Ty * const end = cur + arr._length;
// Перебираем данные
while (cur != end)
{
// Умножаем каждый элемент и сдвигаем указатель на следующий
*cur++ *= val;
}
return result;
}

template<class Ty>
array<Ty> operator*(Ty val, const array<Ty>& arr)
{
return arr*val;
}

template<class Ty>
array<Ty> operator+(const array<Ty>& arr, Ty val)
{
array<Ty> result = arr;
Ty* cur = result._data;
const Ty * const end = cur + arr._length;
while (cur != end)
{
*cur++ += val;
}
return result;
}

template<class Ty>
array<Ty> operator+(Ty val, const array<Ty>& arr)
{
return arr + val;
}

Код:
lo:-10
hi:9
length:20
Array:-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9
Array*10:-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Array+10:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Count:1
Count:2
Count:1
5
Неизвестный
25.12.2009, 11:48
общий
Мих@ил:
Учитывая, что в прошлый раз были проблемы с Вашим компилятором VC++ 6.
Код:
#include <iostream>
#include <cstring>
#include <stdexcept>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::out_of_range;

// Шаблонный класс-массив
template<class T>
class array
{
public:
// Используемые типы
typedef int index_type;
typedef unsigned int size_type;
// Конструкторы
explicit array(size_type length = 10);
array(index_type lo, size_type length);
array(const array<T>& arr);
virtual ~array();
// Оператор присваивания
const array<T> & operator=(const array<T>& arr);
// Возвращает минимальный индекс
index_type lo() const;
// Возвращает максимальный индекс
index_type hi() const;
// Возвращает размер
size_type length() const;
// Индексаторы
T & operator[](index_type index);
const T & operator[](index_type index) const;
static size_t count();
private:
static size_t _count;
// Мин. индекс
index_type _lo;
// Длина
size_type _length;
// Данные
T* _data;
template<class Ty> friend array<Ty> operator*(const array<Ty>& arr, Ty val);
template<class Ty> friend array<Ty> operator+(const array<Ty>& arr, Ty val);
};

template<class T> size_t array<T>::_count=0;


// Оператор вывода для массива
template<class T>
ostream& operator<<(ostream& stream, const array<T>& arr)
{
for (typename array<T>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
stream << arr[i] << ' ';
}
return stream;
}

template<class T>
array<T>::array(typename array<T>::size_type length)
: _lo(1)
, _length(length)
, _data(new T[length]())
{
++_count;
}

template<class T>
array<T>::array(index_type lo, size_type length)
: _lo(lo)
, _length(length)
, _data(new T[length]())
{
++_count;
}

// Оператор копирования
template<class T>
array<T>::array(const array<T>& arr)
: _lo(arr._lo) // Копируем нижний индекс
, _length(arr._length) // Копируем длину массива
, _data(new T[arr._length]()) // Создадим массив с такой же длиной
{
// Копируем данные
memcpy(_data, arr._data, _length * sizeof (T));
++_count;
}

template<class T>
array<T>::~array()
{
if(_data)
{
delete[] _data;
_data=0;
--_count;
}
}

template<class T>
const array<T>& array<T>::operator=(const array<T>& arr)
{
if (this != &arr)
{
delete[] _data;
_data=new T[_length = arr._length]();
_lo = arr._lo;
memcpy(_data, arr._data, _length * sizeof (T));
++_count;
}
return *this;
}

template<class T>
typename array<T>::index_type array<T>::lo() const
{
return _lo;
}

template<class T>
typename array<T>::index_type array<T>::hi() const
{
return _lo - 1 + _length;
}

template<class T>
typename array<T>::size_type array<T>::length() const
{
return _length;
}

template<class T>
T& array<T>::operator[](index_type index)
{
if ((index -= _lo) < _length)
{
return *(_data + index);
}
else throw out_of_range("Index out of bounds");
}

template<class T>
const T& array<T>::operator[](index_type index) const
{
if ((index -= _lo) < _length)
{
return *(_data + index);
}
else throw out_of_range("Index out of bounds");
}

template<class T>
size_t array<T>::count()
{
return _count;
}

// Оператор умножения массива на значение
template<class Ty>
array<Ty> operator*(const array<Ty>& arr, Ty val)
{

// Копируем массив в result
array<Ty> result = arr;
// Получим указатель на начало данных
Ty* cur = result._data;
// Указатель на конец данных
const Ty * const end = cur + arr._length;
// Перебираем данные
while (cur != end)
{
// Умножаем каждый элемент и сдвигаем указатель на следующий
*cur++ *= val;
}
return result;
}

template<class Ty>
array<Ty> operator*(Ty val, const array<Ty>& arr)
{
return arr*val;
}

template<class Ty>
array<Ty> operator+(const array<Ty>& arr, Ty val)
{
array<Ty> result = arr;
Ty* cur = result._data;
const Ty * const end = cur + arr._length;
while (cur != end)
{
*cur++ += val;
}
return result;
}

template<class Ty>
array<Ty> operator+(Ty val, const array<Ty>& arr)
{
return arr + val;
}

typedef array<int> int_array;

int main()
{
// Создаем массив из 20 элементов с первым индексом -10
int_array arr(-10, 20);
for (array<int>::index_type i = arr.lo(), end = i + arr.length(); i < end; ++i)
{
arr[i] = i;
}
cout << "lo:" << arr.lo() << endl
<< "hi:" << arr.hi() << endl
<< "length:" << arr.length() << endl;
cout << "Array:" << arr << endl;
cout << "Array*10:" << 10 * arr << endl;
cout << "Array+10:" << 10 + arr << endl;
cout<<"Count:"<<int_array::count()<<endl;
{
int_array b(arr);
cout<<"Count:"<<int_array::count()<<endl;
}
cout<<"Count:"<<int_array::count()<<endl;
return 0;
}
Неизвестный
25.12.2009, 14:15
общий
Micren:
Спасибо!Все работает!
Форма ответа