On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 14.11.12 17:44. Заголовок: Data Structure


Can just guide 1 step by 1 step as long as i can get understanding from you ma?

Write a template class that implements a set of items. A set is a collection of items in which no item occurs more than once. Internally, you may represent the set using the data structure of your choice (e.g. list, arrays, etc). However the class should externally support the following functions:

 Add a new item to the set. If the item is already in the set then nothing happens.
 Remove an item from the set.
 Return the number of items in the set.
 Determine if an item is a member of the set.


for the data structure isn't something like this?
 
class Item{
private:
struct list{
string name;
}
public:
//function

};


Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 19 [только новые]





ссылка на сообщение  Отправлено: 14.11.12 19:04. Заголовок: You can use either d..


You can use either data structure, for example, an array of fixed size.

T a[MAX_SIZE];

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 14.11.12 19:30. Заголовок: so , after the chan..


so , after the changes .
#include <iostream> 
#include <string>
#include <conio.h>

using namespace std;

template< class T >
class Item{
private:
T object[100];
string ItemName;
public:
Item(){ ItemName = "" };
~Item();

static int count;

void addNewItem();
void RemoveItem();
void numOfItem();
void DetermineItem();

};

template< class T >
int Item<T> :: count = 0;

int main(){

system( "pause" );//Pause window
return 0;//Exit program
}



Can you explain for me that
 Return a pointer to a dynamically created array containing each item in the set. The caller of this function is responsible for de-allocating the memory.
what does this mean?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 14.11.12 20:52. Заголовок: What is not clear he..


What is not clear here? You should create a dynamically allocated array copy all elements of your set into this array and return the pointter to itt.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 15.11.12 04:32. Заголовок: i clear with it. i j..


i clear with it. i just don't know why this also in a function of the class .
However the class should externally support the following functions:
and inside got a function :
 Return a pointer to a dynamically created array containing each item in the set. The caller of this function is responsible for de-allocating the memory.
i thought we create a dynamically array in our main only? why it's inside the member function of the class?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 15.11.12 12:07. Заголовок: It is a service of t..


It is a service of the class to provide a raw data of the set.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 15.11.12 17:57. Заголовок: #include <iostre..


#include <iostream> 
#include <string>
#include <conio.h>

using namespace std;

template< class T >
class Set{
private:
T Item[100];
int count;
public:
Set(){ count = 0; };
~Set();

void addNewItem(const T &);
void RemoveItem(const T &);
int numOfItem();
int FindItem(const T &);

};

template< class T >
void Set<T> :: addNewItem( const T &item){
int result = FindItem(item);

//Add new item when FindItem return a value -1
if( result == -1 ){

}
else
cout << endl;//Nothing Happen
}

template< class T >
void Set<T> :: RemoveItem( const T &item ){
int result = FindItem(item);

if( result >= 0 && result < count ){

}
}


template< class T >
int Set<T> :: numofItem(){
return count;
}
template< class T >
int Set<T> :: FindItem( const T &item ){
int result = -1;
for( int i = 0 ; i < count ; i++ ){
if( item == Item ){
result = i;
break;
}
}
return result;
}

int main(){
int choice = 0;
string title;
system( "pause" );//Pause window

cout << "\tSet of items\n--------------------------" << endl
<< "1.Add New Item " << endl
<< "2.Remove an Item " << endl
<< "3.Number of items in the set " << endl
<< "4.Find Item " << endl
<< "5.Get all Items " << endl << endl
<< "Enter Choice : ";

cin >> choice;

switch( choice ){
case 1:{
cout << "Enter title : ";
getline( cin , title );
Set<string> set;
set.addNewItem(title);
break;
}
default:
cout << "Invalid Input ! Please re-enter ! "<< endl;
break;
}
system( "pause" );
return 0;//Exit program
}


here the code i try to done..
can tell me how should i implement for the addNewItem code and delete?
for the delete i don't know how should i
decrease the item . sorry

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 15.11.12 18:22. Заголовок: I did not see all yo..


I did not see all your code yet but I have already some remarks. Let write code in a professional way.

 template< class T >  
class Set{
private:
T Item[100];
int count;
public:
Set(){ count = 0; };
~Set();
void addNewItem(const T &);
void RemoveItem(const T &);
int numOfItem();
int FindItem(const T &);
};


Your class has a container with a fixed size. So it would be good if the user can determine how many elements can be added to your class.
Thus I suggest to name the magic number 100 at least as N and declare it either as const static data member or as an enumerator. The class shall have two functions size() and max_size(). The name size is better than numOfItem because such name is used in standard containers. Also because there can not be negative number of elements then it is better to define N as unsigned int or as size_t and introduce corresponding typedefs. For example

 template< class T >  
class Set{
private:
static const size_t N = 100;
T Item[N];
size_t count;
public:
typedef size_t size_type;
typedef T value_type;

Set() : count( 0 ) {};
~Set();

size_type size() const { return ( count ); }
size_type max_size() const { return ( N ); }

// other member functions.
};



Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 15.11.12 18:51. Заголовок: okay i change the co..


okay i change the code as you stated:
template< class T > 
class Set{
private:
//Cannot be negative number , validation
static const size_t N = 100;
T Item[N];
size_t count;
public:
Set() : count(0){};
~Set();

void addNewItem(const T &);
void RemoveItem(const T &);
size_t size();
size_t max_size();
int FindItem(const T &);

};

template< class T >
void Set<T> :: addNewItem( const T &item){
int result = FindItem(item);

//Add new item when FindItem return a value -1
if( result == -1 ){

}
else
cout << endl;//Nothing Happen
}

template< class T >
void Set<T> :: RemoveItem( const T &item ){
int result = FindItem(item);

if( result >= 0 && result < count ){

}
}

template< class T >
size_t Set<T> :: size() const{
return count;
}

template< class T >
size_t Set<T> :: max_size() const{
return N;
}

template< class T >
int Set<T> :: FindItem( const T &item ){
int result = -1;
for( int i = 0 ; i < count ; i++ ){
if( item == Item ){
result = i;
break;
}
}
return result;
}


the max_size() is for which function ? Get All items? because that is just a accessor?
by the way.
can tell me how should i implement for the addNewItem code and delete?
for the delete i don't know how should i
decrease the item . sorry

thanks ><

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 19.11.12 13:15. Заголовок: #include <iostre..


#include <iostream> 
#include <string>
#include <conio.h>

using namespace std;

template< class T >
class Set{
private:
//Cannot be negative number , validation
static const size_t N = 100;
T Item[N];
size_t count;
public:
Set() : count(0){};
~Set();

void addNewItem(const T &);
void RemoveItem(const T &);
size_t size();
size_t max_size();
int FindItem(const T &);

bool operator==(const Set &set ){ return count == set.count; }
bool operator!=(const Set &set ){ return count != set.count; }

};

template< class T >
void Set<T> :: addNewItem( const T &addData){
// check for duplicate data
bool duplicate = false;
for( int i = 0 ; i < N ; i++ ){
// check if new data is similar to the data in the stack
if( Item == addData )
duplicate = true;
}

// if there are no duplication
if( duplicate == false ){
if( count < N )
stack[count++] = addData;
cout << "Item successfull added ! " << endl;
}
else
cout<<"Entered item already exist in the stack"<<endl;
}

template< class T >
void Set<T> :: RemoveItem( const T &deleteData ){
// declare & initialize variable
bool foundDelete = false;
int index;

// search in the item if the data to be deleted exist
for( int i = 0 ; i < N ; i++ ){
// check if it exist(found)
if( Item == deleteData ){
foundDelete = true;
index = i;
}
}

// if it exists(found)
if( foundDelete == true ){
// shift the item to replace & overwrite the delete data
for( int j = index; j < N-1 ; j++ ){
Item[j]=Item[j+1];
}
count--; // reduce the number items
cout << "Item successfull deleted ! " << endl;
}
else
cout << "Number stack not found ! " << endl;
}

template< class T >
size_t Set<T> :: size() const{
return count;
}

template< class T >
size_t Set<T> :: max_size() const{
return N;
}

int main(){
int choice = 0;
string title;
system( "pause" );//Pause window

cout << "\tSet of items\n--------------------------" << endl
<< "1.Add New Item " << endl
<< "2.Remove an Item " << endl
<< "3.Number of items in the set " << endl
<< "4.Find Item " << endl
<< "5.Get all Items " << endl << endl
<< "Enter Choice : ";

cin >> choice;

switch( choice ){
case 1:{
cout << "\n\tAdd Item\n---------------------- " << endl;
cout << "Enter title : ";
getline( cin , title );
Set<string> set;
set.addNewItem(title);
getch();//Pause window
break;
}
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
cout << "Invalid Input ! Please re-enter ! "<< endl;
break;
}
system( "pause" );
return 0;//Exit program
}


i did it with my own concept !
can have a look for my additem and removeitem.

isn't correct ?
beside that. i need to overload the == and != operator for the object class so my template based set class can determine membership
need i declare my operator overloadiing correctly?


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 20.11.12 22:25. Заголовок: Felicia1234 пишет: ..


Felicia1234 пишет:

 цитата:
beside that. i need to overload the == and != operator for the object class so my template based set class can determine membership



I did not understand what is "object class"?!

Also these operaators are invalid

  	bool operator==(const Set &set ){ return count == set.count; } 
bool operator!=(const Set &set ){ return count != set.count; }


Besides comparing counts they shall compare each element of the containers with each other.

It would be better to define operator != as

  	bool operator!=(const Set &set ){ return ( !( *this == set ) ); }



Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 04:33. Заголовок: #include <iostre..


#include <iostream> 
#include <string>
#include <vector>
#include <iterator>
#include <conio.h>

using namespace std;

template< class T >
class Set{
private:
//Cannot be negative number , validation
static const size_t N = 100;
T Item[N];
size_t count;
public:
Set() : count(0){};

void addNewItem(const T &);
void RemoveItem(const T &);
void FindItem(const T &);
T *GetAllItems() const;
size_t size() const;
size_t max_size() const;

bool operator ==( const Set &set ){
bool match;
if( count == set.count ){
for( int i = 0 ; i < count ; i++ ){
if( Item == set.Item )
match = true;
else{
match = false;
break;
}
}
}
return match;
}
bool operator!=(const Set &set ){
bool match;
if( count == set.count ){
for( int i = 0 ; i < count ; i++ ){
if( Item == set.Item )
match = true;
else{
match = false;
break;
}
}
}
return match;
}

};

template< class T >
void Set<T> :: addNewItem( const T &addData){
// check for duplicate data
bool duplicate = false;
for( int i = 0 ; i < count ; i++ ){
// check if new data is similar to the data in the stack
if( Item == addData )
duplicate = true;
}

// if there are no duplication
if( duplicate == false ){
if( count < N )
Item[count++] = addData;
cout << "Item successfull added ! " << endl << endl;
}
else
cout << "Entered item already exist in the stack" << endl << endl;
}

template< class T >
void Set<T> :: RemoveItem( const T &deleteData ){
// declare & initialize variable
bool foundDelete = false;
int index;

// search in the item if the data to be deleted exist
for( int i = 0 ; i < count ; i++ ){
// check if it exist(found)
if( Item == deleteData ){
foundDelete = true;
index = i;
}
}

// if it exists(found)
if( foundDelete == true ){
cout << "\nItem Found in Set " << endl
<< "1.Delete Item " << endl
<< "2.Cancel " << endl << endl
<< "Enter Choice : ";
int choice = 0;
cin >> choice ;
do{
switch( choice ){
case 1:
// shift the item to replace & overwrite the delete data
for( int j = index; j < N-1 ; j++ ){
Item[j]=Item[j+1];
}
count--; // reduce the number items
cout << "Item successfull deleted ! " << endl << endl;
break;
case 2:
cout << "Process been cancel by user ! " << endl << endl;
break;
default:
cout << "Invalid Input ! Please re-enter ! " << endl << endl;
}
}while( choice != 2 );
}
else
cout << "Number stack not found ! " << endl << endl;
}

template< class T >
void Set<T> :: FindItem( const T &findItem ){
// declare & initialize variable
bool foundItem = false;
int index;

// search in the item if the data to be deleted exist
for( int i = 0 ; i < count ; i++ ){
// check if it exist(found)
if( Item == findItem ){
foundItem = true;
index = i;
}
}

if( foundItem == true ){
cout << findItem << " is a member of the set ! " << endl << endl;
}
else
cout << findItem << " is not a member of the set ! " << endl << endl;
}

template< class T >
T* Set<T> :: GetAllItems() const {
T *result = new T[count];
for( int i = 0 ; i < count ; i++ ){
result = Item;
}
/*for( int i = 0 ; i < count ; i++ ){
cout << result << endl;
}*/
return result;
}

template< class T >
size_t Set<T> :: size()const{
return count;
}

template< class T >
size_t Set<T> :: max_size()const{
return N;
}

class firstclass{};
class secondclass{};

int main(){
int choice = 0;
string title;
Set<string>set;
Set theset;

do{
cout << "\tSet of items\n--------------------------" << endl
<< "0.Exit Program " << endl
<< "1.Add New Item " << endl
<< "2.Remove an Item " << endl
<< "3.Number of items in the set " << endl
<< "4.Find Item " << endl
<< "5.Get all Items " << endl << endl
<< "Enter Choice : ";

cin >> choice;

switch( choice ){
case 0:
cout << "Program Been Terminated by User ! " << endl;
getch();
break;
case 1:{
firstclass firstobject;
secondclass secondobject;
set.addNewItem<firstclass>(firstobject);
set.addNewItem(secondobject);
cin.ignore();
string title = "";
cout << "\n\tAdd Item\n---------------------- " << endl;
cout << "Enter title : ";
getline( cin , title );
set.addNewItem(title);
getch();//Pause window
break;
}
case 2:{
// DELETE
//prompt of user input
cin.ignore();
string title = "";
cout << "\n\tDelete Item\n-------------------------" << endl;
cout << "Enter the data to delete : ";
getline( cin , title );
set.RemoveItem(title);
getch();
break;
}
case 3:{
cout << "Number of item in the set : " << set.size() << endl << endl;
getch();//Pause window
break;
}
break;
case 4:{
cin.ignore();
string title = "";
cout<<"\n\tFind Item\n-----------------------"<<endl;
cout << "Enter Item to find : ";
getline( cin , title );
cout << endl;
set.FindItem( title );
getch();
break;
}
case 5:
/*cout << set.GetAllItems() << endl << endl;*/
//int getAll; getAll = set.GetAllItems();
getch();
break;
default:
cout << "Invalid Input ! Please re-enter ! "<< endl;
break;
}
}while( choice != 0 );
system( "pause" );
return 0;//Exit program
}


this is what i done so far. can working . but i having problem that pass the class inside my set. can u teach me about that?
see my switch case 1

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 09:58. Заголовок: I did not yet look t..


I did not yet look through all your code but I am already seeing that operators == and != are invalid.

 	bool operator ==( const Set &set ){ 
bool match;
if( count == set.count ){
for( int i = 0 ; i < count ; i++ ){
if( Item == set.Item )
match = true;
else{
match = false;
break;
}
}
}
return match;
}


Variable match was not initialized. So if count != set.count the code block after this if statement will be skipped and you will return undefined value of match.
Also as I said early it is better to define operator != as negation of the operator ==.

You could use standard algorithm std::equal that in fact has the same realization with some exceptions as your loop. If to use it then the operator == could look more simply and clear

 bool operator ==( const Set &rhs ) const 
{
return ( count == rhs.count && std::equal( Item, Item + count, rhs.Item ) );
}


Take into account the trailing qualifier const in the function declaration.

Also it would be better to make these operator functions as non-class functions.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 11:07. Заголовок: okay. i change the b..


okay. i change the bool operator == and != with new replacement
bool operator ==( const Set &rhs ) const  
{
return ( count == rhs.count && std::equal( Item, Item + count, rhs.Item ) );
}


but now , if i wan to pass class object ? how should i pass it to my set?
i declare it as
class firstclass; 
class secondclass;

firstclass firstobject;
secondclass secondobject;

Set.addnewItem(firstobject);

how should i pass my class inside the set to add the item as object??



Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 12:45. Заголовок: bool operator ==( co..


bool operator ==( const Set &rhs ){ 
return ( count == rhs.count && equal( Item, Item + count, rhs.Item ) );
}
bool operator!=(const Set &set ){
return ( count != rhs.count && equal( Item, Item + count, rhs.Item ) );
}


isn't correct ? Please correct me if i keep make mistake for it and mind to see post above? how should i pass the class object?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 17:22. Заголовок: bool operator ==( c..


 bool operator ==( const Set &rhs ) const 
{
return ( count == rhs.count && std::equal( Item, Item + count, rhs.Item ) );
}

bool operator !=( const Set &rhs ) const
{
return ( !( *this == rhs ) );
}


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 17:34. Заголовок: class firstclass { p..


Set<string>set; 

do{
cout << "\tSet of items\n--------------------------" << endl
<< "0.Exit Program " << endl
<< "1.Add New Item " << endl
<< "2.Remove an Item " << endl
<< "3.Number of items in the set " << endl
<< "4.Find Item " << endl
<< "5.Get all Items " << endl << endl
<< "Enter Choice : ";

cin >> choice;

switch( choice ){
case 0:
cout << "Program Been Terminated by User ! " << endl;
getch();
break;
case 1:{
int choice1 = 0;
cout << "\n\tAdd Record\n---------------------" << endl
<< "1.Add Item with String Type " << endl
<< "2.Add Item with Object Type " << endl
<< "3.Add Item with integer Type " << endl << endl
<< "Enter Choice : ";
cin >> choice1;
switch( choice1 ){
case 1:{
cin.ignore();
string title = "";
cout << "\n\tAdd Item [String Type]\n------------------------------- " << endl;
cout << "Enter title : ";
getline( cin , title );
set.addNewItem(title);
cout << "String Type Item Added Successfull " << endl;
getch();
break;
}
case 2:{
int countObject = 0;
char Y = ' ';
do{
cout << "Do you want to create data type of object ? [Y/N] : ";
cin >> Y;
if( Y == 'Y' || Y == 'y' ){
countObject++;
if( countObject == 1){
Set<firstclass> theset;
firstclass firstobject;
theset.addNewItem(firstobject);
cout << "Object type added successfull " << endl;
}
else if( countObject == 2 ){
Set<secondclass> theset1;
secondclass secondobject;
theset1.addNewItem(secondobject);
cout << "Object type added successfull " << endl;
}
else{
cout << "User only defined two classes ! Cannot add class type anymore ! " << endl << endl;
}
}
else if( Y =='N' || Y == 'n' )
cout << "Task been cancelled by user ! " << endl << endl;
}while( Y =='Y' || Y == 'y' );
break;
}
case 3:{
Set<int> Setint;
int integertype = 0;
cout << "\n\tAdd Item [Integer Type]\n--------------------------" << endl
<< "Enter number : ";
cin >> integertype;
while( cin.fail() ){
cin.clear();
cin.ignore(100,'\n');
cout << "Invalid input ! Only integer type allow ! " << endl << endl;
cout << "Enter number : ";
cin >> integertype;
}
cout << "Integer Type Item Added Successfull " << endl;
Setint.addNewItem(integertype);
getch();//Pause window
break;
}
}
getch();//Pause window
break;
}
case 2:{
// DELETE
//prompt of user input
cin.ignore();
string title = "";
cout << "\n\tDelete Item\n-------------------------" << endl;
cout << "Enter the data to delete : ";
getline( cin , title );
set.RemoveItem(title);
getch();
break;
}
case 3:{
cout << "Number of item in the set : " << set.size() << endl << endl;
getch();//Pause window
break;
}
break;
case 4:{
cin.ignore();
string title = "";
cout<<"\n\tFind Item\n-----------------------"<<endl;
cout << "Enter Item to find : ";
getline( cin , title );
cout << endl;
set.FindItem( title );
getch();
break;
}
case 5:{
string *getAll = set.GetAllItems();
getch();
delete []getAll;
break;
}
default:
cout << "Invalid Input ! Please re-enter ! "<< endl;
break;
}
}while( choice != 0 );



It's work already . but the problem is
can you see my each case 1 for first switch??
then the got 3 choice with different type . after i add in the type . when i try to get number of set. it fail . only string type number can be count other object or integer type cannot get all . if the code here are hard to c . mind to c the thread and reply?? please. thanks
http://www.cplusplus.com/forum/beginner/84902/2/

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 17:53. Заголовок: Yes, if the class de..


Yes, if the class design is correct then count shall be increased by 1. If it is not true then look method addNewItem to determine what is wrong.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 21.11.12 18:12. Заголовок: mind to c post above..


mind to c post above? i just edit it ..

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 23.11.12 01:02. Заголовок: I do not see any sen..


I do not see any sense in your second menu where you are trying to add an object of type int because you are adding it to the local container Set<int> Setint;

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 28
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет