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

Программа с шаблоном

20.04.2011, 19:33. Показов 473. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Помогите найти ошибку в сортировке по названию.
books.h
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
#ifndef _BOOKS_
#define _BOOKS_
 
#include <string.h>
#include <iostream>
 
using namespace std;
 
#pragma warning (disable:4267)
#pragma warning (disable:4996)
 
#define LENGTH_DEFAULT      0x20
 
class CString;
class CBook;
template <class Item>
class CIterator;
template <class Item>
class CList;
 
class CString
{
protected:
    char * pStr;
    unsigned short uBufSize;
public:
    CString();
    CString(char *);
    CString(CString &);
    ~CString();
 
    void AllocBuffer(unsigned short);
    operator char * ();
    CString & operator + (char *);
    void operator += (char *);
    void operator = (char *);
    bool operator == (char *);  
    bool operator > (char *);
    bool operator < (char *);
    bool operator <= (char *);
    bool operator >= (char *);
};
 
class CBook
{
protected:
    CString sTitle;
    CString sAuthor;
    float fPrice;   
    unsigned short uYear;
public:
    CBook();
    CBook(CBook &);
    CBook(CString & title, CString & author, float price, unsigned short year); //куча конструкторов
    ~CBook();
 
    CString & Title();
    void Title(CString &);
    CString & Author();
    void Author(CString &);
    float Price();
    void Price(float);
    unsigned short Year();
    void Year(unsigned short);
    bool operator == (CBook &); 
};
 
template <class Item> class CList
{
public:
    CList * pPrev;
    CList * pNext;
    Item * pItem;
public:
    CList();
    ~CList();
    void Add(Item *, int (_cdecl *)(Item &, Item &));
    bool Remove(Item &);        
    CIterator<Item> & GetHead();    
    void Free();
};
 
template <class Item>
class CIterator
{
protected:
    CList<Item> * pHead;
    CList<Item> * pCurrent;
    unsigned short uID;
public:
    CIterator();
    CIterator(CList<Item> *);
    ~CIterator();
 
    Item & Data();
    bool GotoNext();
    bool GotoPrev();
    void Reset();
    unsigned short ID();
};
 
#endif
menu.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "books.h"
 
#define CMD_ADD             0x01
#define CMD_REMOVE          0x02
#define CMD_CHANGE          0x03
#define CMD_TITSORT         0x04
#define CMD_YEARSORT        0x05
#define CMD_PRICESORT       0x06
#define CMD_PRINT           0x07
 
void MenuProc();
void ShowMenu();
void Add(); 
void Remove();
void Change();
void TitSort();
void PriceSort();
void YearSort();
void Print();
void MenuProc();
int YearCmp(CBook &, CBook &);
int AuthorCmp(CBook &, CBook &);
int TitCmp(CBook &, CBook &);
main.cpp
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
170
171
172
173
174
175
#include "books.h"
#include "menu.h"
 
using namespace std;
 
CString::CString()
{
    this->pStr=new char [LENGTH_DEFAULT];
    this->uBufSize=LENGTH_DEFAULT;      //конструктор класса строк, размер буффера всегда кратен 32 байтам
    this->pStr[0]='\0';
    return;
}
 
CString::CString(char * str)
{
    unsigned short len=0;
 
    len=strlen(str);
    if((len % LENGTH_DEFAULT) == 0) this->uBufSize=len;
    else this->uBufSize=(unsigned short)(((len / LENGTH_DEFAULT)+1)*LENGTH_DEFAULT);    //ещё конструктор
    this->pStr=new char [this->uBufSize];
    strcpy(this->pStr, str);
    return;
}
 
CString::CString(CString & str)
{
    this->uBufSize=str.uBufSize;
    this->AllocBuffer(str.uBufSize);
    strcpy(this->pStr, str.pStr);
    return;
}
CString::~CString()
{
    delete [] this->pStr;
    this->pStr=0;
    this->uBufSize=0;           //и деструктор
    return;
}
 
void CString::AllocBuffer(unsigned short size) {    //распределить буффер
    unsigned short len=0;
    char * old=0;
 
    size++;
    len=strlen(this->pStr);
    if(len >= size) return;         //если новый размер меньше длины стрки, то возврат
    old=this->pStr;
    if((size % LENGTH_DEFAULT) == 0) this->uBufSize=size;
    else this->uBufSize=(unsigned short)(((size / LENGTH_DEFAULT)+1)*LENGTH_DEFAULT);
    this->pStr=new char [this->uBufSize];       //иначе перещитать размер буфера, перераспределить память, скопировать
    strcpy(this->pStr, old);
    delete [] old;
    return;
}
 
CString::operator char * ()
{   return this->pStr;  }       //оператор приведения в массив символьного тип
 
CString & CString::operator + (char * str)
{
    CString * res=0;
 
    res=new CString(* this);        //конкатенация с возвратом результата
    (* res) += str;
    return (* res);
}
 
void CString::operator += (char * str)
{
    unsigned short myLen=0, itLen=0;    //добавить к текущей строке ещё одну
    char * copy=0;
 
    itLen=strlen(str);
    myLen=strlen(this->pStr);
    if(this->uBufSize > (itLen+myLen)) strcat(this->pStr, str); //если буфер вмещает, копируем
    else {
        copy=new char [myLen+1];
        strcpy(copy, this->pStr);
        this->AllocBuffer(itLen+myLen);             //иначе перераспределяем и копируем
        strcpy(this->pStr, copy);
        strcat(this->pStr, str);
        delete [] copy;
    }
    return;
}
 
void CString::operator = (char * str)
{
    unsigned short len=0;
 
    len=strlen(str);
    if(this->uBufSize > len) strcpy(this->pStr, str);       //такие же манипуляции с буфером
    else {
        this->AllocBuffer(len);
        strcpy(this->pStr, str);
    }
    return;
}
bool CString::operator == (char * str)              //сравнения
{ return (strcmp(this->pStr, str) == 0); }
 
bool CString::operator > (char * str)
{   return (strcmp(this->pStr, str) == 1);  }
 
bool CString::operator < (char * str)
{   return (strcmp(this->pStr, str) == -1);  }
 
bool CString::operator >= (char * str)
{   return (strcmp(this->pStr, str) >= 0);  }
 
bool CString::operator <= (char * str)
{   return (strcmp(this->pStr, str) <= 0);  }
 
CBook::CBook()
{
    this->sAuthor="<unknown author>\0";     //конструктор заполняет поля значениями по умолчанию
    this->sTitle="<unknown title>\0";
    this->fPrice=0.0;
    this->uYear=1900;
    return;
}
 
CBook::CBook(CBook & book)
{
    this->sTitle=(char *)book.sTitle;
    this->sAuthor=(char *)book.sAuthor;         //конструктор-копировщик
    this->uYear=book.uYear;
    this->fPrice=book.fPrice;
    return;
}
CBook::CBook(CString & tit, CString & aut, float pr, unsigned short yr) //конструктор с параметрами
{
    this->sTitle=(char *)tit;
    this->sAuthor=(char *)aut;
    this->uYear=yr;
    this->fPrice=pr;
    return;
}
CBook::~CBook() //просто деструктор
{return;} 
 
CString & CBook::Title()        //последовательность гет-методов и сет-методов
{   return this->sTitle;    }
 
void CBook::Title(CString & tit)
{   this->sTitle=tit; return;   }
 
CString & CBook::Author()
{   return this->sAuthor;   }
 
void CBook::Author(CString & aut)
{   this->sAuthor=aut; return;  }
 
float CBook::Price()
{   return this->fPrice;    }
 
void CBook::Price(float pr)
{   this->fPrice=pr; return;    }
 
unsigned short CBook::Year()
{   return this->uYear;     }
 
void CBook::Year(unsigned short yr)
{   this->uYear=yr; return;     }
bool CBook::operator == (CBook & book)
{ return (this->fPrice == book.fPrice && this->uYear == book.uYear &&
            this->sAuthor == book.sAuthor && this->sTitle == book.sTitle);
}
 
 
void main()
{
    MenuProc();
}
menu.cpp
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include "menu.h"
 
CList<CBook> * bookList=0;
unsigned short uBooks=0;
 
template <class Item>
CList<Item>::CList()
{
    this->pPrev=0;
    this->pNext=0;
    this->pItem=0;
    return;
}
 
template <class Item>
CList<Item>::~CList()   
{
    this->Free();
    return;
}
 
template <class Item>
void CList<Item>::Add(Item * it, int (_cdecl * cmp)(Item & it1, Item & it2))
{
    CList * cur=0, * prev=0, * addIt=0;
 
    if(this->pNext == 0){
        this->pNext=new CList;
        this->pNext->pItem=it;
        this->pNext->pNext=0;
        this->pNext->pPrev=0;
        return;
    }
    
    prev=0; cur=this->pNext;
    addIt=new CList();
    while((cur != 0) && (cmp(* it, * cur->pItem) > 0)){
        prev=cur;
        cur=cur->pNext;
    }
    addIt->pNext=cur;
    addIt->pPrev=prev;
    addIt->pItem=it;
    if(prev == 0) this->pNext=addIt;
        else prev->pNext=addIt;
    if(cur != 0) cur->pPrev=addIt;
    return;
}
 
template <class Item>
bool CList<Item>::Remove(Item & it)
{
    CList * cur=0, * prev=0;
 
    if(this->pNext == 0) return false;
    prev=0; cur=this->pNext;
    while((cur != 0) && !((* cur->pItem) == it)){
        prev=cur;
        cur=cur->pNext;
    }
    if(cur == 0) return false;
    if(cur->pPrev == 0){
        this->pNext=cur->pNext;
        if(this->pNext != 0)
            this->pNext->pPrev=0;
    }
    else {
        cur->pPrev->pNext=cur->pNext;
        if(cur->pNext != 0) cur->pNext->pPrev=cur->pPrev;
    }
    //delete cur->pItem;
    //delete cur;
    return true;
}
 
template <class Item>
CIterator<Item> & CList<Item>::GetHead()
{
    CIterator<Item> * res=0;
 
    res=new CIterator<Item>(this);
    return (* res);
}
 
template <class Item>
void CList<Item>::Free()
{
    CList<Item> * cur=0, * prev=0;
 
    if(this->pNext == 0) return;
    if(this->pNext->pNext == 0){
        delete this->pNext->pItem;
        this->pNext->pItem=0;
        delete this->pNext;
        return;
    }
    cur=this->pNext->pNext;
    prev=this->pNext;
    while(cur != 0)
    {
        delete prev->pItem;
        prev=cur;
        cur=cur->pNext;
    }
    return;
}
 
template <class Item>
CIterator<Item>::CIterator()
{
    this->pCurrent=0;
    this->pHead=0;
    this->uID=0;
    return;
}
 
template <class Item>
CIterator<Item>::CIterator(CList<Item> * lst)
{
    this->pHead=lst->pNext;
    this->pCurrent=lst->pNext;
    this->uID=1;
    return;
}
 
template <class Item>
CIterator<Item>::~CIterator()
{   return;     }
 
 
template <class Item>
Item & CIterator<Item>::Data()
{
    if(this->pCurrent != 0 && this->pCurrent->pItem != 0) return (* this->pCurrent->pItem);
    return (* new Item);
}
 
template <class Item>
bool CIterator<Item>::GotoNext()
{
    if(this->pCurrent == 0 || this->pCurrent->pNext == 0) return false;
    pCurrent=pCurrent->pNext;
    this->uID++;
    return true;
}
 
template <class Item>
bool CIterator<Item>::GotoPrev()
{
    if(this->pCurrent == 0 || this->pCurrent->pPrev == 0) return false;
    pCurrent=pCurrent->pPrev;
    this->uID--;
    return true;
}
 
template <class Item>
void CIterator<Item>::Reset()
{   
    this->pCurrent=this->pHead;
    this->uID=1;    
    return;
}
 
template <class Item>
unsigned short CIterator<Item>::ID()
{   return this->uID;   }
 
int YearCmp(CBook & b1, CBook & b2)
{   return b1.Year() - b2.Year();   }
 
int PriceCmp(CBook & b1, CBook & b2)
{   return (int)(b1.Price() - b2.Price());  }
 
int TitCmp(CBook & b1, CBook & b2)
{   return strcmp(b1.Title(), b2.Title());  }
 
void PrintMenu()
{
    cout<<"\t********** MENU **********\0"<<endl;
    cout<<CMD_ADD<<" - add a new book\0"<<endl;
    cout<<CMD_REMOVE<<" - remove existing book\0"<<endl;
    cout<<CMD_CHANGE<<" - change existing book data\0"<<endl;
    cout<<CMD_TITSORT<<" - sort list by title\0"<<endl;
    cout<<CMD_YEARSORT<<" - sort list by year\0"<<endl;
    cout<<CMD_PRICESORT<<" - sort list by price\0"<<endl;
    cout<<CMD_PRINT<<" - print the list\0"<<endl;
    cout<<"  any another to exit\0"<<endl;
    cout<<endl;
}
 
void Add()
{
    CString tit, aut;
    unsigned short year=0;
    float price=0;
 
    cout<<"   ***** Adding a book *****\0"<<endl;
    cout<<"Book's title: \0"; cin>>(char *)tit;
    cout<<"Book's author: \0"; cin>>(char *)aut;
    cout<<"Book's price: \0"; cin>>price;
    cout<<"Book's production year: \0"; cin>>year;
 
    bookList->Add(new CBook(tit, aut, price, year), YearCmp);
    uBooks++;
    return;
}
 
void Remove()
{
    CString tit;
    CIterator<CBook> iter=bookList->GetHead();
    
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    cout<<"   ***** Removing a book *****\0"<<endl;
    cout<<"Enter book's title: \0"; cin>>(char *)tit;
    if(iter.Data().Title() == tit){
            bookList->Remove(iter.Data());
            return;
    }
    while(iter.GotoNext() == true)
        if(iter.Data().Title() == tit){
            bookList->Remove(iter.Data());
            uBooks--;
            return;
        }
    cout<<"Such book was not found!\0"<<endl;
}
void Change()
{
    CString tit, aut;
    unsigned short year=0;
    float price=0;
    CIterator<CBook> iter=bookList->GetHead();
    
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    cout<<"   ***** Changing book's data *****\0"<<endl;
    cout<<"Current book's title: \0"; cin>>(char *)tit;
    if(iter.Data().Title() == tit){
            bookList->Remove(iter.Data());
            cout<<"New book's title: \0"; cin>>(char *)tit;
            cout<<"New book's author: \0"; cin>>(char *)aut;
            cout<<"New book's price: \0"; cin>>price;
            cout<<"New book's production year: \0"; cin>>year;
            bookList->Add(new CBook(tit, aut, price, year), YearCmp);
            return;
        }
    while(iter.GotoNext() == true)
        if(iter.Data().Title() == tit){
            bookList->Remove(iter.Data());
            cout<<"New book's title: \0"; cin>>(char *)tit;
            cout<<"New book's author: \0"; cin>>(char *)aut;
            cout<<"New book's price: \0"; cin>>price;
            cout<<"New book's production year: \0"; cin>>year;
            bookList->Add(new CBook(tit, aut, price, year), YearCmp);
            return;
        }
    cout<<"Such book was not found!\0"<<endl;
}
 
 
void TitSort()
{
    CIterator<CBook> iter=bookList->GetHead();
    CList<CBook> * newList=0;
 
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    newList=new CList<CBook>;
    newList->Add(new CBook(iter.Data()), TitCmp);
    while(iter.GotoNext() == true)
        newList->Add(new CBook(iter.Data()), TitCmp);
    bookList->Free();
    bookList=newList;
    cout<<"   ***** List was sorted by title *****\0"<<endl;
    return;
}
 
void PriceSort()
{
    CIterator<CBook> iter=bookList->GetHead();
    CList<CBook> * newList=0;
 
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    newList=new CList<CBook>;
    newList->Add(new CBook(iter.Data()), PriceCmp);
    while(iter.GotoNext() == true)
        newList->Add(new CBook(iter.Data()), PriceCmp);
    bookList->Free();
    bookList=newList;
    cout<<"   ***** List was sorted by price *****\0"<<endl;
    return;
}
 
void YearSort()
{
    CIterator<CBook> iter=bookList->GetHead();
    CList<CBook> * newList=0;
 
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    newList=new CList<CBook>;
    newList->Add(new CBook(iter.Data()), YearCmp);
    while(iter.GotoNext() == true)
        newList->Add(new CBook(iter.Data()), YearCmp);
    bookList->Free();
    bookList=newList;
    cout<<"   ***** List was sorted by year *****\0"<<endl;
    return;
}
void Print()
{
    CIterator<CBook> iter=bookList->GetHead();
    
    if(uBooks == 0){
        cout<<"The list is empty!\0"<<endl;
        return;
    }
    cout<<"   ***** Books' list *****\0"<<endl;
    cerr<<iter.ID()<<". "<<iter.Data().Author()<<": \""<<iter.Data().Title()<<"\", "
        <<iter.Data().Year()<<"y., $"<<iter.Data().Price()<<endl;
    while(iter.GotoNext() == true){
        cerr<<iter.ID()<<". "<<iter.Data().Author()<<": \""<<iter.Data().Title()<<"\", "
            <<iter.Data().Year()<<"y., $"<<iter.Data().Price()<<endl;
    }
}
 
void MenuProc()
{
    unsigned short cmd=0, loop=0;
 
    bookList=new CList<CBook>;
    while(cmd <= CMD_PRINT)
    {
        if((loop % 0x08) == 0)
            PrintMenu();
        cout<<"Your choice: \0"; cin>>cmd;
        if(cmd == CMD_ADD) Add();
        else if(cmd == CMD_REMOVE) Remove();
        else if(cmd == CMD_CHANGE) Change();
        else if(cmd == CMD_TITSORT) TitSort();
        else if(cmd == CMD_PRICESORT) PriceSort();
        else if(cmd == CMD_YEARSORT) YearSort();
        else if(cmd == CMD_PRINT) Print();
        else cmd=CMD_PRINT+1;
        loop++;
        cout<<endl;
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.04.2011, 19:33
Ответы с готовыми решениями:

Ошибка с шаблоном
Собсно,только начал изучать шаблоны,кажется,что-то упустил,ну в общем вот: #include &lt;iostream&gt;...

Работа со списком, шаблоном
Помогите, пожалуйста, реализовать класс List, представляющий список, элементами которого являются...

Работа с шаблоном класса
Приветствую. Есть задание: 1. Создать шаблон заданного класса. Определить конструкторы,...

Поиск по файле за шаблоном
Как произвести поиск по файлу? У файле есть имена и номера. Например: Олег 0973205615 Миша...

0
20.04.2011, 19:33
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
20.04.2011, 19:33
Помогаю со студенческими работами здесь

Бинарное дерево с шаблоном
Пишу бинарное дерево типа BST&lt;Key, Value&gt;. Значениями хочу сделать любые типы данных. По-этому...

Error C4430 с шаблоном
Доброго времени суток. Не могу разобраться, в чем проблема. Хелп :) Выдаёт ошибку ...

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

Сортировка массива с шаблоном
Помогите пожалуйста с задачкой....Нужно отсортировать 3 массива (отдельно) с помощью шаблона + к...


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

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