Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
5 / 5 / 1
Регистрация: 09.09.2012
Сообщений: 227
1

Дополнить класс динамическим массивом

07.02.2013, 07:46. Показов 955. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго всем времи суток!!!

Возникла проблема - создан класс "sequence" нужно дописать его так, чтобы он использовал динамический массив как private member переменную.

Класс должен отличаться от написанного:
- номер элементов, который может быть сохранён в "sequence" должен лимитироваться только количеством памяти поступной в свободном хранении (free store). При добавлении нового элемента размер массива данных должен автоматически увеличиваться.
- Необходимо определить: copy конструктор, assignment operator и destructor.
- Конструктор должен иметь default аргумент, который позволит пользователю установить первоначальную вместимость класса "sequence".
- Необходима функция - resize -которая позволит пользователю четко установить ёмкость "sequence".


Header file "sequence2":
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// FILE: sequence2.h
// CLASS PROVIDED: sequence (part of the namespace main_savitch_4)
// There is no implementation file provided for this class since it is
// an exercise from Chapter 4 of "Data Structures and Other Objects Using C++"
//
// TYPEDEFS and MEMBER CONSTANTS for the sequence class:
//   typedef ____ value_type
//     sequence::value_type is the data type of the items in the sequence. It
//     may be any of the C++ built-in types (int, char, etc.), or a class with a
//     default constructor, an assignment operator, and a copy constructor.
//
//   typedef ____ size_type
//     sequence::size_type is the data type of any variable that keeps track of
//     how many items are in a sequence.
//
//   static const size_type DEFAULT_CAPACITY = _____
//     sequence::DEFAULT_CAPACITY is the initial capacity of a sequence that is
//     created by the default constructor.
//
// CONSTRUCTOR for the sequence class:
//   sequence(size_t initial_capacity = DEFAULT_CAPACITY)
//     Postcondition: The sequence has been initialized as an empty sequence.
//     The insert/attach functions will work efficiently (without allocating
//     new memory) until this capacity is reached.
//
// MODIFICATION MEMBER FUNCTIONS for the sequence class:
//   void resize(size_type new_capacity)
//     Postcondition: The sequence's current capacity is changed to the 
//     new_capacity (but not less that the number of items already on the
//     list). The insert/attach functions will work efficiently (without
//     allocating new memory) until this new capacity is reached.
//
//   void start( )
//     Postcondition: The first item on the sequence becomes the current item
//     (but if the sequence is empty, then there is no current item).
//
//   void advance( )
//     Precondition: is_item returns true.
//     Postcondition: If the current item was already the last item in the
//     sequence, then there is no longer any current item. Otherwise, the new
//     current item is the item immediately after the original current item.
//
//   void insert(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted in the sequence
//     before the current item. If there was no current item, then the new entry 
//     has been inserted at the front of the sequence. In either case, the newly
//     inserted item is now the current item of the sequence.
//
//   void attach(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted in the sequence after
//     the current item. If there was no current item, then the new entry has 
//     been attached to the end of the sequence. In either case, the newly
//     inserted item is now the current item of the sequence.
//
//   void remove_current( )
//     Precondition: is_item returns true.
//     Postcondition: The current item has been removed from the sequence, and the
//     item after this (if there is one) is now the new current item.
//
// CONSTANT MEMBER FUNCTIONS for the sequence class:
//   size_type size( ) const
//     Postcondition: The return value is the number of items in the sequence.
//
//   bool is_item( ) const
//     Postcondition: A true return value indicates that there is a valid
//     "current" item that may be retrieved by activating the current
//     member function (listed below). A false return value indicates that
//     there is no valid current item.
//
//   value_type current( ) const
//     Precondition: is_item( ) returns true.
//     Postcondition: The item returned is the current item in the sequence.
//
// VALUE SEMANTICS for the sequence class:
//    Assignments and the copy constructor may be used with sequence objects.
//
// DYNAMIC MEMORY USAGE by the List
//   If there is insufficient dynamic memory, then the following functions
//   throw a BAD_ALLOC exception: The constructors, insert, attach. 
 
#ifndef MAIN_SAVITCH_SEQUENCE_H
#define MAIN_SAVITCH_SEQUENCE_H
#include <cstdlib>  // Provides size_t
 
namespace main_savitch_4
{
    class sequence
    {
    public:
        // TYPEDEFS and MEMBER CONSTANTS
        typedef double value_type;
        typedef std::size_t size_type;
        static const size_type DEFAULT_CAPACITY = 30;
        // CONSTRUCTORS and DESTRUCTOR
        sequence(size_type initial_capacity = DEFAULT_CAPACITY);
        sequence(const sequence& source);
    ~sequence( );
        // MODIFICATION MEMBER FUNCTIONS
    void resize(size_type new_capacity);
        void start( );
        void advance( );
        void insert(const value_type& entry);
        void attach(const value_type& entry);
        void remove_current( );
        void operator =(const sequence& source);
        // CONSTANT MEMBER FUNCTIONS
        size_type size( ) const;
        bool is_item( ) const;
        value_type current( ) const;
    private:
        value_type* data;
        size_type used;
        size_type current_index;
    size_type capacity;
    };
}
 
#endif
Implementation file sequence 1:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Section CSC-161-500 - Computer Science II: C++
// File Name: sequence1.cxx
// Student: Anna Pavlenko
// Homework Number: Homework Two
// Description: sequence1.cxx - an implementation file for the sequence class, version 1
// Last Changed:
    
// FILE:    sequence1.cxx
//CLASS IMPLEMENTED: sequence
//INVARIANT for sequence class:
//   1. The number of items in the sequence is in the member variable used;
//   2. For an empty sequence, we do not care what is stored in any of data; for a
//      non-empty sequence the items in the bag are stored in data[0] through
//      data[used-1]. The items in a sequence are arranged in an order, one after another
 
#include <iostream> 
#include <algorithm>
#include <cassert> // Provides assert function
#include "sequence1.h" // With value_type defined as double
using namespace std;
 
namespace main_savitch_3
{
    // MODIFICATION MEMBER FUNCTIONS
    sequence::sequence() 
    {
     current_index = 0;
     used = 0;
    }    
    
    void sequence::start( )
    {
    current_index = 0;
    }   
    
     void sequence::advance( )
    {
    assert(it_item());      
    current_index++;
    }             
   
    //insert member function
    
    void sequence::insert(const value_type&entry)
    {
        size_type i;
         
        assert(size() < CAPACITY);
        
        if(!is_item())
           current_index = 0;
        for (i = used; i > current_index; --i)
        {
           data[i] = data[i - 1];
           data[current_index] = entry;
           used++;
        }
     }
 
   // attach member function
   
     void sequence::attach(const value_type& entry);
     {
        size_type i;
         
        assert(size() < CAPACITY);
        
        if(!is_item())
           data[current_index] = entry;
           
        else 
        {  
        for (i = used; i > current_index+1; --i)
           data[i] = data[i - 1];
           data[current_index+1] = entry;
           current_index++;
        }
        used++;
     }
     
     
     void sequence::remove_current( )
    {
        size_type i;
         
        assert(is_item( ));
 
       for (i = current_index+1; i < used; i++)
       data[i-1] = data[i];
       used--;
    }
     
   
    // CONSTANT MEMBER FUNCTIONS
      sequence::size_type sequence::size( ) const
       {
       return used; 
       }
 
      bool sequence::is_item( ) const
      {    
      return (current_index < used);
      }
 
      sequence::value_type sequence::current( ) const
      {  
       assert(is_item( ));                      
       return data[current_index];
      }
 
      
      
    system("Pause");
    return 0;
}

Please, help!!!
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
07.02.2013, 07:46
Ответы с готовыми решениями:

Класс с динамическим массивом
доброго времени суток! помогите мне немножко: создать клас vector для сохранения массиву,...

Класс с содержащимся динамическим массивом
Возникла необходимость создать свой объект, с внутренним массивом данных, к которому возможно...

Класс для работы с n-мерным динамическим массивом
При работе с 3-мерным динамическим массивом я чего-то &quot;в пня въехал&quot;. Начал &quot;рыскать&quot;, а...

Создать класс для работы с двумерным динамическим массивом чисел
Создать класс для работы с двумерным динамическим массивом чисел. Методы: -заполнить массив...

3
Модератор
3388 / 2160 / 352
Регистрация: 13.01.2012
Сообщений: 8,378
07.02.2013, 11:48 2
Цитата Сообщение от QWERY_2012 Посмотреть сообщение
- номер элементов, который может быть сохранён в "sequence" должен лимитироваться только количеством памяти поступной в свободном хранении (free store). При добавлении нового элемента размер массива данных должен автоматически увеличиваться.
- Необходимо определить: copy конструктор, assignment operator и destructor.
- Конструктор должен иметь default аргумент, который позволит пользователю установить первоначальную вместимость класса "sequence".
- Необходима функция - resize -которая позволит пользователю четко установить ёмкость "sequence".
1 измените функцию добавления элемента: если свободных мест нет - выделяйте новый кусок памяти имеющий размер на некое количество элементов больше чем текущий, копируйте туда содержимое текущего куска, удаляйте текущий кусок, изменяйте указатель на текущий кусок и размер на новые, добавляйте элемент
2 у вас вообще конструкторы пока не очень то и определены - не ясно откуда возьмется data - под него надо выделить память. в пустом конструкторе обнулить data. в конструкторе с параметром выделить кусок вмещающий указанное в качестве параметра кол-во элементов. в конструкторе копирования - выделить кусок размером с блок данных в копируемом объекте и скопировать туда data, заполнить остальные поля взяв их значение из копируемого объекта
3 во время присваивания - если принимающий кусок больше чем передаваемый - очищать его (сбрасывая счетчики) и копировать в него содержимое передаваемого куска, если меньше - удалять, выделять память размером с передаваемый кусок и копировать его
4 в деструкторе освобождать выделенную память
5 default аргумент у вас есть - DEFAULT_CAPACITY
6 что значит четко установить емкость? поджать data до фактического размера? тогда если data имеет хвост выделяйте память четкого размера, копируйте туда заполненную часть data, освобождайте data, обновляйте указатель на data новым куском, обновляйте другие поля
1
4773 / 2582 / 894
Регистрация: 29.11.2010
Сообщений: 5,590
07.02.2013, 12:39 3
Это пример из справочника по плохому стилю кода, что-ли? Плохо практически везде, поэтому не буду перечислять, а приведу сразу реализацию. По спецификации, в том же плохом стиле, хоть местами и не удержался, сделал по-лучше.


Компилил, не проверял -- рука не поднимается.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <stdexcept>
 
class sequence {
 public:
  // TYPEDEFS and MEMBER CONSTANTS
  typedef double value_type;
  typedef std::size_t size_type;
  static const size_type DEFAULT_CAPACITY = 30;
  // CONSTRUCTORS and DESTRUCTOR
  sequence(size_type initial_capacity = DEFAULT_CAPACITY);
  sequence(const sequence& source);
  ~sequence();
  // MODIFICATION MEMBER FUNCTIONS
  void resize(size_type new_capacity);
  void start();
  void advance();
  void insert(const value_type& entry);
  void attach(const value_type& entry);
  void remove_current();
  void operator =(const sequence& source);
  void copy_from(const sequence &source);
  // CONSTANT MEMBER FUNCTIONS
  size_type size() const;
  bool is_item() const;
  value_type current() const;
 private:
  value_type* data;
  size_type used;
  size_type current_index;
  size_type capacity;
};
 
// CONSTRUCTOR for the sequence class:
//   sequence(size_t initial_capacity = DEFAULT_CAPACITY)
//     Postcondition: The sequence has been initialized as an empty sequence.
//     The insert/attach functions will work efficiently (without allocating
//     new memory) until this capacity is reached.
sequence::sequence(size_type initial_capacity)
  : data(0), used(0), current_index(0), capacity(0) {
  resize(initial_capacity);
}
 
// VALUE SEMANTICS for the sequence class:
//    Assignments and the copy constructor may be used with sequence objects.
sequence::sequence(const sequence& source)
  : data(0), used(0), current_index(0), capacity(0) {
  copy_from(source);
}
 
sequence::~sequence() {
  delete [] data;
}
 
// COPYING FUNCTION
// copies a sequence into current sequence
void sequence::copy_from(const sequence &source) {
  if (this != &source) {
    delete [] this->data;
    this->used = source.used;
    this->current_index = source.current_index;
    this->capacity = source.capacity;
    this->data = new value_type[capacity];
    for (size_type i = 0; i < this->used; ++i) {
      this->data[i] = source.data[i];
    }
  }
}
 
//   void resize(size_type new_capacity)
//     Postcondition: The sequence's current capacity is changed to the 
//     new_capacity (but not less that the number of items already on the
//     list). The insert/attach functions will work efficiently (without
//     allocating new memory) until this new capacity is reached.
void sequence::resize(size_type new_capacity) {
  new_capacity = (new_capacity < used) ? used : new_capacity;
  // no meaningless action
  if (new_capacity == capacity) {
    return;
  }
  value_type *new_data = new value_type[new_capacity];
  for (size_type i = 0; i < used; ++i) {
    new_data[i] = data[i];
  }
  delete [] data;
  data = new_data;
  capacity = new_capacity;
}
 
//   void start( )
//     Postcondition: The first item on the sequence becomes the current item
//     (but if the sequence is empty, then there is no current item).
void sequence::start() {
  current_index = 0;
}
 
//   void advance( )
//     Precondition: is_item returns true.
//     Postcondition: If the current item was already the last item in the
//     sequence, then there is no longer any current item. Otherwise, the new
//     current item is the item immediately after the original current item.
void sequence::advance() {
  ++current_index;
}
 
//   void insert(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted in the sequence
//     before the current item. If there was no current item, then the new entry 
//     has been inserted at the front of the sequence. In either case, the newly
//     inserted item is now the current item of the sequence.
void sequence::insert(const value_type &entry) {
  if (size() >= capacity) {
    resize(size() + 1);
  }
  for (size_type i = size(); i > current_index; --i) {
    data[i] = data[i - 1];
  }
  ++used;
  data[current_index] = entry;
}
 
//   void attach(const value_type& entry)
//     Postcondition: A new copy of entry has been inserted in the sequence after
//     the current item. If there was no current item, then the new entry has 
//     been attached to the end of the sequence. In either case, the newly
//     inserted item is now the current item of the sequence.
void sequence::attach(const value_type& entry) {
  if (is_item()) {
    advance();
  }
  insert(entry);
}
 
//   void remove_current( )
//     Precondition: is_item returns true.
//     Postcondition: The current item has been removed from the sequence, and the
//     item after this (if there is one) is now the new current item.
void sequence::remove_current() {
  if (is_item()) {
    for (size_type i = current_index; i < size(); ++i) {
      data[i] = data[i + 1];
    }
    --used;
  }
}
 
//   size_type size( ) const
//     Postcondition: The return value is the number of items in the sequence.
sequence::size_type sequence::size() const {
  return used;
}
 
//   bool is_item( ) const
//     Postcondition: A true return value indicates that there is a valid
//     "current" item that may be retrieved by activating the current
//     member function (listed below). A false return value indicates that
//     there is no valid current item.
bool sequence::is_item() const {
  return current_index < used;
}
 
//   value_type current( ) const
//     Precondition: is_item( ) returns true.
//     Postcondition: The item returned is the current item in the sequence.
sequence::value_type sequence::current() const {
  if (!is_item()) {
    throw std::overflow_error("no more elements in sequence");
  }
  return data[current_index];
}
1
5 / 5 / 1
Регистрация: 09.09.2012
Сообщений: 227
07.02.2013, 22:08  [ТС] 4
Спасибо за помошь!!!

Буду разбираться. Для меня тема Классов и ОПП авсолютно не понятны пока.
0
07.02.2013, 22:08
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
07.02.2013, 22:08
Помогаю со студенческими работами здесь

Проблема с динамическим массивом
#include &quot;stdafx.h&quot; #include&lt;iostream&gt; #include&lt;conio.h&gt; using namespace std; int...

Странность с динамическим массивом
Меня в тупик поставило следующая ошибка (&quot;Название исполняемого файла&quot; has triggered a breakpoint.)...

Проблема с динамическим массивом
Имею 2 динамических массива. Но если в 1 массиве запись данных и вывод на консоль осуществляются...

Работа с динамическим массивом
Помогите, пожалуйста. В чем проблема? Компилирует, но выполнять не хочет. Надо вставить элемент в...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru