Sorted sequence class

Question1:

Suppose that you implement a sequence where the value_type has a comparison operator < to determine when one item is “less than” another item. For example, integers, double numbers, and characters all have such a comparison operator (and classes that you implement yourself may also be given such a comparison). Rewrite the sequence class using a new class name, sorted_sequence. In a sorted sequence, the insert function always inserts a new item so that all the items stay in order from smallest to largest. There is no attach function. All the other functions are the same as the original sequence class.

My answer:

sorted_sequence.h

// FILE: sorted_sequence1.h
// CLASS PROVIDED: sorted_sequence (part of the namespace main_savitch_3)
// There is no implementation file provided for this class since it is
// an exercise from Section 3.2 of "Data Structures and Other Objects Using C++"
//
// TYPEDEFS and MEMBER CONSTANTS for the sorted_sequence class:
//   typedef ____ value_type
//     sorted_sequence::value_type is the data type of the items in the sorted_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
//     sorted_sequence::size_type is the data type of any variable that keeps track of
//     how many items are in a sorted_sequence.
//
//   static const size_type CAPACITY = _____
//     sorted_sequence::CAPACITY is the maximum number of items that a sorted_sequence can hold.
//
// CONSTRUCTOR for the sorted_sequence class:
//   sorted_sequence( )
//     Postcondition: The sorted_sequence has been initialized as an empty sorted_sequence.
//
// MODIFICATION MEMBER FUNCTIONS for the sorted_sequence class:
//   void start( )
//     Postcondition: The first item on the sorted_sequence becomes the current item
//     (but if the sorted_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
//     sorted_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)
//     Precondition: size( ) < CAPACITY.
//     Postcondition: A new copy of entry has been inserted in the sorted_sequence
//     before the current item. If there was no current item, then the new entry 
//     has been inserted at the front of the sorted_sequence. In either case, the newly
//     inserted item is now the current item of the sorted_sequence.
//
//   void remove_current( )
//     Precondition: is_item returns true.
//     Postcondition: The current item has been removed from the sorted_sequence, and the
//     item after this (if there is one) is now the new current item.
//
// CONSTANT MEMBER FUNCTIONS for the sorted_sequence class:
//   size_type size( ) const
//     Postcondition: The return value is the number of items in the sorted_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 sorted_sequence.
//
// VALUE SEMANTICS for the sorted_sequence class:
//    Assignments and the copy constructor may be used with sorted_sequence objects.

#ifndef MAIN_SAVITCH_SEQUENCE_H
#define MAIN_SAVITCH_SEQUENCE_H
#include <cstdlib>  // Provides size_t

namespace main_savitch_3
{
    class sorted_sequence
    {
    public:
        // TYPEDEFS and MEMBER CONSTANTS
        typedef double value_type;
        typedef std::size_t size_type;
        static const size_type CAPACITY = 30;
        // CONSTRUCTOR
        sorted_sequence( );
        // MODIFICATION MEMBER FUNCTIONS
        void start( );
        void advance( );
        void insert(const value_type& entry);
        void remove_current( );
        void insert_head(const value_type& entry);
        void remove_head();
        void insert_tail(const value_type& entry);
        void end();
        sorted_sequence operator -(sorted_sequence& entry);
        void operator -=(sorted_sequence& entry);
        value_type operator [](size_type index) const;
        // void operator =(const sorted_sequence& entry);
        // CONSTANT MEMBER FUNCTIONS
        size_type size( ) const;
        bool is_item( ) const;
        value_type current( ) const;
    private:
        value_type data[CAPACITY];
        size_type used;
        size_type current_index;
    };
}

#endif

sorted_sequence.cpp

#include "sorted_sequence.h"
#include <iostream>
#include <cassert>

using namespace std;
using namespace main_savitch_3;

sorted_sequence::sorted_sequence(){
    // If there is a current item, then it lies in data[current_index];
    // if there is no current item, then current_index equals used.
    current_index = used = 0;
}

void sorted_sequence::start(){
    current_index = 0;
}

void sorted_sequence::advance(){
    current_index = (current_index + 1) % CAPACITY;
    // the max of current_index is CAPACITY-1
}

void sorted_sequence::insert(const value_type& entry){
    assert(size() < CAPACITY);
    size_type i;
    if(current_index != used){
        for(i = current_index; i < size(); i++);
    }
    if(used == 0){
        data[0] = entry;
        used++;
        current_index = 0;
        return;
    }
    for(; i != 0 && entry < data[i-1]; i--){
        data[i] = data[i-1];
    }
    data[i] = entry;
    used++;
    current_index = i;
    return;
}

void sorted_sequence::remove_current(){
    assert(is_item());
    if(current_index == size()-1){
        // the last one
        used--;
    } else {
        for(size_type i = current_index; i < size(); i++){
            data[i] = data[i+1];
        }
        used--;
    }
}

sorted_sequence::size_type sorted_sequence::size() const{
    return used;
}

bool sorted_sequence::is_item() const{
    if(current_index >= used){
        return false;
    } else {
        return true;
    }
}

sorted_sequence::value_type sorted_sequence::current() const{
    assert(is_item());
    return data[current_index];
}

void sorted_sequence::insert_head(const value_type& entry){
    assert(size() < CAPACITY);
    size_t i = size();
    for(; i > 0; i--){
        data[i] = data[i-1];//数据后移
    }
    // i = 0
    data[i] = entry;
    used++;
}

void sorted_sequence::remove_head(){
    assert(size() > 0);
    size_t i = 0;
    for(; i < size(); i++){
        data[i] = data[i+1];
    }
    used--;
}

void sorted_sequence::insert_tail(const value_type& entry){
    assert(size() < CAPACITY);
    data[size()] = entry;
    used++;    
}

void sorted_sequence::end(){
    current_index = size() - 1;
}

sorted_sequence sorted_sequence::operator -(sorted_sequence& entry){
    sorted_sequence res;
    for(this->start(); this->is_item(); this->advance()){
        res.insert(this->current());
    }
    for(entry.start(); entry.is_item(); entry.advance()){
        for(res.start(); res.is_item(); res.advance()){
            if(res.current() == entry.current()){
                res.remove_current();
            }
        }
    }
    return res;
}

void sorted_sequence::operator -=(sorted_sequence& entry){
    for(entry.start(); entry.is_item(); entry.advance()){
        for(start(); is_item(); advance()){
            if(entry.current() == current()){
                remove_current();
            }
        }
    }
}

sorted_sequence::value_type sorted_sequence::operator [](size_type index) const{
    assert(index >= 0 && index < size());
    return data[index];
}

// void sorted_sequence::operator =(const sorted_sequence& entry){
//     for(entry.start(); entry.is_item(); entry.advance()){
//         this->insert(entry.current());
//     }
// }

main.cpp

// FILE: sorted_sequence_test.cxx
// An interactive test program for the new sorted_sequence class
#include <cctype>       // Provides toupper
#include <iostream>     // Provides cout and cin
#include <cstdlib>      // Provides EXIT_SUCCESS
#include "sorted_sequence.h"  // With value_type defined as double
using namespace std;
using namespace main_savitch_3;

// PROTOTYPES for functions used by this test program:
void print_menu( );
// Postcondition: A menu of choices for this program has been written to cout.

char get_user_command( );
// Postcondition: The user has been prompted to enter a one character command.
// The next character has been read (skipping blanks and newline characters), 
// and this character has been returned.

void show_sorted_sequence(sorted_sequence display);
// Postcondition: The items on display have been printed to cout (one per line).

double get_number( );
// Postcondition: The user has been prompted to enter a real number. The
// number has been read, echoed to the screen, and returned by the function.


int main( )
{
    sorted_sequence test, test1, test2; // A sorted_sequence that we’ll perform tests on
    char choice;   // A command character entered by the user
    
    cout << "I have initialized an empty sorted_sequence of real numbers." << endl;

    do
    {
        print_menu( );
        choice = toupper(get_user_command( ));
        switch (choice)
        {
            case '!': test.start( );
                      break;
            case '@': test.end();
                      break;
            case '+': test.advance( );
                      break;
            case '?': if (test.is_item( ))
                          cout << "There is an item." << endl;
                      else 
                          cout << "There is no current item." << endl;
                      break;
            case 'C': if (test.is_item( ))
                           cout << "Current item is: " << test.current( ) << endl;
                      else
                          cout << "There is no current item." << endl;
                      break;
            case 'P': show_sorted_sequence(test);
                      break;
            case 'S': cout << "Size is " << test.size( ) << '.' << endl;
                      break;
            case 'I': test.insert(get_number( ));
                      break;
            case 'R': test.remove_current( );
                      cout << "The current item has been removed." << endl;
                      break;
            case 'H': test.insert_head(get_number());
                      break;
            case 'L': test.remove_head();
                      cout << "The item in the head has been removed." << endl;
                      break;     
            case 'Z': test.insert_tail(get_number());
                      cout << "A new item has been inserted into the tail." << endl;
                      break;
            case 'T': test1.insert(1);
                      test1.insert(2);
                      test1.insert(3);
                      cout << "test:" << endl;
                      show_sorted_sequence(test);
                      cout << "test1:" << endl;
                      show_sorted_sequence(test1);
                      test2 = test - test1;
                      cout << "test2 = test - test1, its result is" << endl;
                      show_sorted_sequence(test2);
                      test -= test1;
                      cout << "test -= test1, its result is" << endl;
                      show_sorted_sequence(test);
                      break;
            case 'G': cout << "The item is " << test[get_number()] << endl;
                      break;
            case 'Q': cout << "Ridicule is the best test of truth." << endl;
                      break;
            default:  cout << choice << " is invalid." << endl;
        }
    }
    while ((choice != 'Q'));

    return EXIT_SUCCESS;
}

void print_menu( )
// Library facilities used: iostream.h
{
    cout << endl; // Print blank line before the menu
    cout << "The following choices are available: " << endl;
    cout << " !   Activate the start( ) function" << endl;
    cout << " @   Activate the end() function" << endl;
    cout << " +   Activate the advance( ) function" << endl;
    cout << " ?   Print the result from the is_item( ) function" << endl;
    cout << " C   Print the result from the current( ) function" << endl;
    cout << " P   Print a copy of the entire sorted_sequence" << endl;
    cout << " S   Print the result from the size( ) function" << endl;
    cout << " I   Insert a new number with the insert(...) function" << endl;
    cout << " R   Activate the remove_current( ) function" << endl;
    cout << " H   Insert a new item with insert_head() function" << endl;
    cout << " L   Remove an item with remove_head() function" << endl;
    cout << " Z   Insert a new item with insert_tail() function" << endl;
    cout << " T   Test the operator - and -=" << endl;
    cout << " G   Test the operator []" << endl;
    cout << " Q   Quit this test program" << endl;
}

char get_user_command( )
// Library facilities used: iostream
{
    char command;

    cout << "Enter choice: ";
    cin >> command; // Input of characters skips blanks and newline character

    return command;
}

void show_sorted_sequence(sorted_sequence display)
// Library facilities used: iostream
{
    for (display.start( ); display.is_item( ); display.advance( ))
        cout << display.current( ) << endl;
}

double get_number( )
// Library facilities used: iostream
{
    double result;
    
    cout << "Please enter a real number for the sorted_sequence: ";
    cin  >> result;
    cout << result << " has been read." << endl;
    return result;
}

结果:

I have initialized an empty sorted_sequence of real numbers.

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: I
Please enter a real number for the sorted_sequence: 6
6 has been read.

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: I
Please enter a real number for the sorted_sequence: 5
5 has been read.

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: I
Please enter a real number for the sorted_sequence: 9
9 has been read.

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: I
Please enter a real number for the sorted_sequence: 0
0 has been read.

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: P
0
5
6
9

The following choices are available:
 !   Activate the start( ) function
 @   Activate the end() function
 +   Activate the advance( ) function
 ?   Print the result from the is_item( ) function
 C   Print the result from the current( ) function
 P   Print a copy of the entire sorted_sequence
 S   Print the result from the size( ) function
 I   Insert a new number with the insert(...) function
 R   Activate the remove_current( ) function
 H   Insert a new item with insert_head() function
 L   Remove an item with remove_head() function
 Z   Insert a new item with insert_tail() function
 T   Test the operator - and -=
 G   Test the operator []
 Q   Quit this test program
Enter choice: Q
Ridicule is the best test of truth.

  1. Data Structures and Other Objects Using C++ ( Fourth Edition ) Michael Main, Walter Savitch. p180 ↩︎

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Memories off

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值