處理資料的方式為將資料丟進Function中處理
const int SIZE = 10;
enum Status { EMPTY, OCCUPIED };
struct Set {
int element[SIZE];
Status status[SIZE];
int element_no;
};
void set_initialization(Set& foo){
for (int i = 0; i < SIZE; i++){
foo.status[i] = EMPTY;
foo.element_no = 0;
}
}
bool insert_element(Set& s, int data){
if (s.element_no == SIZE)
return false;
for (int i = 0; i < SIZE; i++){
if (s.status[i] == EMPTY){
s.element[i] = data;
s.status[i] = OCCUPIED;
s.element_no++;
return true;
}
}
}
int delete_element(Set& s, int data){
int count = 0;
for (int i = 0; i < SIZE; i++){
if (s.status[i] == OCCUPIED && s.element[i] == data){
s.status[i] = EMPTY;
s.element_no--;
count++;
}
}
return count;
}
void print_set(const Set& foo){
for (int i = 0; i < SIZE; i++){
if (foo.status[i] == OCCUPIED)
cout << foo.element[i] << ' ';}
cout << endl;
}
int main()
{
Set mySet;
set_initialization(mySet);
print_set(mySet);
insert_element(mySet, 5);
insert_element(mySet, 7);
insert_element(mySet, 8);
print_set(mySet);
delete_element(mySet, 4);
print_set(mySet);
delete_element(mySet, 5);
print_set(mySet);
return 0;
}
將函式原型提出
const int SIZE = 10;
enum Status { EMPTY, OCCUPIED };
struct Set {
int element[SIZE];
Status status[SIZE];
int element_no;
};
//函示原型
void set_initialization(Set&);
bool insert_element(Set&, int);
int delete_element(Set&, int);
void print_set(const Set&);
int main()
{
...
}
void set_initialization(Set& foo){
...
}
bool insert_element(Set& s, int data){
...
}
int delete_element(Set& s, int data){
...
}
void print_set(const Set& foo){
...
}
class Set
{
private:
int element[SIZE];
Status status[SIZE];
int element_no;
public:
void set_initialization();
bool insert_element(int);
int delete_element(int);
void print_set() const; //const代表此函示不會改變data member
};
int main()
{
Set mySet;
mySet.set_initialization();
mySet.print_set();
mySet.insert_element(5);
mySet.insert_element(7);
mySet.insert_element(8);
mySet.print_set();
mySet.delete_element(4);
mySet.print_set();
mySet.delete_element(5);
mySet.print_set();
return 0;
}
void Set::set_initialization(){
for (int i = 0; i < SIZE; i++){
status[i] = EMPTY;
element_no = 0;
}
}
bool Set::insert_element(int data){
if (element_no == SIZE)
return false;
for (int i = 0; i < SIZE; i++){
if (status[i] == EMPTY){
element[i] = data;
status[i] = OCCUPIED;
element_no++;
return true;
}
}
}
int Set::delete_element(int data){
int count = 0;
for (int i = 0; i < SIZE; i++){
if (status[i] == OCCUPIED && element[i] == data){
status[i] = EMPTY;
element_no--;
count++;
}
}
return count;
}
void Set::print_set() const{
for (int i = 0; i < SIZE; i++){
if (status[i] == OCCUPIED)
cout << element[i] << ' ';
}
cout << endl;
}