Hello

I have to do a sorted list code according to some instructions. a friend and I worked on this, and we pretty much ended up with the same code, his worked, but mine isnt, even though its exactly same!

I have been trying for hours figuring how to make a file and why the 5.5 in main() in x.retrieve keeps resulting in errors. we are supposed to read a list from a file, (named float.txt, or can be IN visual studio which i forgot how to to do, and searched the internet for an hour and nothing good comes up)and insert, delete, and retrieve an item. the program did that, but only to my friend. I have no idea why isnt this working out for me!

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#define MAX_ITEMS  10
using namespace std;
typedef   float  ItemType;

float list[10];

class SortedList
{
private:
    int length;
    ItemType values[MAX_ITEMS];

    struct Node
    {ItemType data;
    Node* next;
    }typedef *nodeptr;

    nodeptr location;
    nodeptr trailing;
    nodeptr head;
    Node* listdata;

    int currentPos;

public:
    SortedList(){ length = 0; currentPos=-1; location = NULL; head = NULL; };  // default constructor

    bool IsFull() // test if the list is full
    {
        if (length < 9)
            return false;
        else
            return true;
    }

    void MakeEmpty()
    {
        nodeptr z;
        while (listdata != NULL)
        {
            z = listdata;
            listdata = listdata->next;
            delete z;
        }
        length = 0; // let length=0
    } 

    void InsertItem(ItemType x) // insert x into the list
    {
        bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;

        if (head != NULL)
        {
            location = head;
            while (location->next != NULL)
            {
                location = location->next;

            }
            location->next = z; length++;
        }
        else
            head = z;
    }

    void DeleteItem(ItemType x) // delete x from the list
    {nodeptr y = NULL;
    location = head;
    trailing = head;
    while (location != NULL&& location->data != x)
    {
        trailing = location;
        location = location->next;
    }
    if (location == NULL)
    {
        cout << "ERROR! Deletion value nonexistant." << endl;
        delete y;
    }
    else
    {
        y = location;
        location = location->next;
        trailing->next = location;
        delete y; length--;
        cout << x << " was DELETED." << endl << endl;
    }
    }

    /*bool IsFull() // test if the list is full
    {
        nodeptr location;
        try
        {
            location = new Node;
            delete location;
            return false;
        }
        catch (bad_alloc exception)
        {
            return true;
        }
    }*/

    void Lengthls(){ cout << length << endl; }   // return length

    void RetrieveItem(ItemType &x, bool &found) // retrieve x from the list, the boolean result is stored in found
    {
        location = 0;

        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR!" << x << " NOT FOUND." << endl;
        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;

            cout << x << " was FOUND." << endl;
        }
    }

    void ResetList() // currentPos=-1
    {
        currentPos = -1;
    }

    float GetNextItem() // get the next element from the list with respect to the currentPos
    {
        currentPos++; 
        float y = list[currentPos];
        return y;
    }

    void printlist()
    {
        location = head;
        while (location != NULL)
        {
        cout << location->data << endl;
        location = location->next;
        }
    }
};

/*void SortedList::InsertItem(ItemType x)
{
    bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;

        if (head != NULL)
        {
            location = head;
            while (location->next != NULL)
            {
                location = location->next;

            }
            location->next = z;
        }
        else
            head = z;
}*/

/*void SortedList::DeleteItem(ItemType x)
{
    nodeptr y = NULL;
    location = head;
    trailing = head;
    while (location != NULL&& location->data != x)
    {
        trailing = location;
        location = location->next;
    }
    if (location == NULL)
    {
        cout << "ERROR! Deletion value nonexistant." << endl;
        delete y;
    }
    else
    {
        y = location;
        location = location->next;
        trailing->next = location;
        delete y;
        cout << x << " was DELETED." << endl << endl;
    }
}*/

/*void SortedList::RetrieveItem(ItemType &x, bool &found)
{
    location = 0;

        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR! NOT FOUND." << endl;

        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;

            cout << x << " was FOUND" << endl;
        }
}*/

int main()
{
    SortedList x;
    ifstream inFile; ofstream output;
    inFile.open("C:\\Users\\name\\Documents\\Visual Studio 2013\\Projects\\CIS 200 project 2\\CIS 200 project 2 myname q2\\CIS 200 project 2 Ques.2\\float.txt");
    string line;

    int i;
    for (i = 0; i < 10; i++)
    {
        getline(inFile, line);

        list[i] =::atof(line.c_str());

        x.InsertItem(list[i]);
    }

    x.ResetList();
    x.InsertItem(100);
    x.printlist();
    cout << endl << "The length is: "; x.Lengthls();

    cout << endl;
    cout << "The list that is made is: " << endl << endl;

    x.DeleteItem(2);

    x.printlist();

    cout << endl;

    bool allAboutLists;
    x.RetrieveItem(5.5, allAboutLists);

    cout << endl;
    cout << "Is the List FULL?: " << boolalpha << x.IsFull() << endl;

    cout << "The next item is: " << x.GetNextItem() << endl;

    x.ResetList();

    output.open("C:\\Users\\name\\Documents\\Visual Studio 2013\\Projects\\CIS 200 project 2\\CIS 200 project 2 myname q2\\CIS 200 project 2 Ques.2\\output.txt");
    for (int file = 0; file<10; file++)
    {
        output << x.GetNextItem() << endl;
    }

    system("pause");
    return 0;
}

line 240: Suggestion: Save yourself a lot of grief by shortening that path down. In Visual Studio you can move the projects to another folder. I always put projects in a folder directly off c:, such as c:\dvlp That makes it a lot easier to specify specific project paths.

line 244: how do you know there will be at least 10 lines in the file? What if there are only 5, or there are 50? A more general way to code it without knowing beforehand how many lines are in the file is like this:

int i = 0;
while(getline(inFile, line))
    {
        list[i] =::atof(line.c_str());
        x.InsertItem(list[i]);
        ++i;
    }

Or even better yet

    int i = 0;
    while(infile >> list[i] )
        {
            x.InsertItem(list[i]);
            ++i;
        }

Why do you need float list[10] ? You can just insert it directly without first reading into list.

    float n;
    while(infile >> n )
        {
            x.InsertItem(n);
        }

Edited 2 Years Ago by Ancient Dragon

we are supposed to read a list from a file, (named float.txt, or can be IN visual studio which i forgot how to to do, and searched the internet for an hour and nothing good comes up)

If memory serves, what you have to do for that is right click on Solution Explorer->Resource Files and select Add->Existing Items and browse to the file in question.

line 121: You can not test two floats or doubles for equality due to possible rounding errors in memory variable. For example if you assign the value 5.5 to a float, in memory it might actually be 5.500001.

One way to handle that is to use integers instead of floats. So if you want 1 decimal place then multiply the float by 10 and assigne it to an integer. Then you can safely use equality tests on the integers.

Here is another thread on that very topic.

Edited 2 Years Ago by Ancient Dragon

A few recommendations:

  • The first thing I would do with this sort of project is separate the class declaration and implementation from the program using them. If you put the class declaration in a header file, and the functions (those which are more than, say, three lines long) into a separate source file, it would improve the modularity of your code.

  • The immediate problem you are having with RetrieveItem() is because you are attempting to pass a literal as a reference value. As I will explain shortly, this function probably should be redefined anyway.

  • It would make more sense to define Node separate from the SortedList class, as there are some functions (as explained below) where it would make more sense to pass a Node as the return type.

  • RetrieveItem() currently takes two reference values as its arguments, one of which it uses to pass back a return value. It would make more sense to pass the comparison number as a value, as you don't change it, and give the Boolean value as the return type. However, I would instead recommend eliminating the bool outright, and returning the Node pointer instead.

  • Why do you set a limit of 10 items on the list? The entire purpose of using a linked list is flexibility in the size of the list; otherwise, an array wouls make more sense. In any case, you have a function to check the size of the list, but you don't actually restrict the list's size anywhere.

  • Given that most functions operating on floating-point numbers actually promote them to doubles, it would probably make more sense to use double for your data type. On a related note, the function strtod() preferred these days over atof(), as the latter allows you to set an end point in the string and has more tightly defined behavior for cases of invalid input.

  • Where are you using listdata? I would eliminate it, as it isn't needed. Similarly, the only places you use trailing are locally within DeleteItem() and RetrieveItem(); I would remove it from the object properties and re-declare it locally in those functions.

Sorry everyone, I completely frgot last time by accident i put stop getting replies from daniweb and never knew how to set it back to get them, but anyways i got this code and now its working 85% i'd say. i only find trouble in not being sequetial. my professor wants it in sequence to screen AND to the ouput file, and idk how to do that. here is the code i worked on ALL NIGHT :(

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define MAX_ITEMS  10

using namespace std;

typedef   float  ItemType;

float list[10];

class SortedList
{
private:
    int length;
    ItemType values[MAX_ITEMS];

    struct Node
    {
        ItemType data;
        Node* next;
    }typedef *nodeptr;

    nodeptr location;
    nodeptr trailing;
    nodeptr head;
    Node* listdata;

    int currentPos;

public:
    SortedList(){ length = 0; currentPos = -1; listdata = NULL; location = NULL; head = NULL; }; // default constructor: lenght=0, currentPos=-1

    bool IsFull() // test if the list is full
    {
        if (length < 9)
            return false;
        else
            return true;
    }; 

    void MakeEmpty()
    {
        nodeptr z;
        while (listdata != NULL)
        {
            z = listdata;
            listdata = listdata->next;
            delete z;
        }
        length = 0; // let length=0
        ;
    };    

    void InsertItem(ItemType x) // insert x into the list
    {
        bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;

        if (head != NULL)
        {
            location = head;
            while (location->next != NULL)
            {
                location = location->next;
            }
            location->next = z; length++;
        }
        else
            head = z;
    };   

    void DeleteItem(ItemType x) // delete x from the list
    {
        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR! Could NOT detect Deletion Value." << endl;
            delete y;
        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;
            delete y; length--;
            cout << x << " was DELETED." << endl << endl;
        }
    };  

    void Lengthls(){ cout << length << endl; }; // return length

    void RetrieveItem(ItemType x, bool &found) // retrieve x from the list, the boolean result is stored in found
    {
        location = 0;

        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR! " << x << " NOT found!" << endl;
        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;

            cout << endl;
            cout << x << " was FOUND." << endl;
        }
    };  

    void ResetList(){ currentPos = -1; }; // currentPos=-1

    float GetNextItem() // get the next element from the list with respect to the currentPos
    {
        currentPos++;
        float y = list[currentPos];
        return y;
    }

    void printlist()
    {
        location = head;
        while (location != NULL)
        {
            cout << location->data << endl;
            location = location->next;
        }
    }
};

int main()
{
    SortedList x;
    ifstream input; ofstream output;
    string line;
    bool allAboutLists;

    input.open("float.txt");

    for (int i = 0; i<10; i++)
    {
        getline(input, line);

        list[i] = ::atof(line.c_str());

        x.InsertItem(list[i]);
    }

    x.ResetList();

    cout << "The following is the list that's been made:" << endl << endl;

    x.InsertItem(64);
    x.printlist();
    cout << endl;
    x.DeleteItem(64);
    x.printlist();

    x.RetrieveItem(7.1, allAboutLists);
    cout << endl;

    cout << "Is the list full?: " << boolalpha << x.IsFull() << endl;
    cout << "The next item is: ";
    for (int i = 0; i < 10; i++)
    {
        cout << x.GetNextItem() << endl;
    }
    x.ResetList();

    output.open("output.txt");

    for (int f = 0; f < 10; f++)
    {
        output << x.GetNextItem() << endl;
    }
    cout << endl << "The length is: "; x.Lengthls(); cout << endl;

    system("pause");
    return 0;
}

I have to do a sorted list code according to some instructions.

What are the instructions?

Can you just use the STL list and the STL sort ?

or ...

Do you need to code your own class List and supply your own code to do a sort?

Even if you need to 'roll your own code' (bottom up) ...
it is often helpful to code the solution, firstly, using the STL ...

Then, when you have that all working well ... substitute in your own (pre-tested) list and sort.

Sorting a file, via reading it at first into a list, is conceptually very simple to code ... as this short demo of reading in a text file of 10 integers, indicates:

// listFromFileSorted/cpp //

#include <iostream>
#include <fstream>
#include <list>


using namespace std;

const char* FNAME = "myList.txt"; // example file to read and sort
/*
3 4 1 6 9 0 2 7 5 8
*/


void print( const list < int >& myLst )
{
    list < int > :: const_iterator it;
    for( it = myLst.begin(); it != myLst.end(); ++it )
        cout << *it << ' ';
}

int main()
{
    // read list from file
    ifstream fin( FNAME );
    if( fin )
    {
        list < int > myLst;
        int tmp;
        while( fin >> tmp )
            myLst.push_back( tmp );
        fin.close();

        cout << "Before sort ...\n";
        print( myLst );

        myLst.sort() ; // calls STL list sort

        cout << "\n\nAfter sort ...\n";
        print( myLst );

    }
    else
        cout << "\nThere was a problem opening file: "
             << FNAME << endl;
}

Edited 2 Years Ago by David W: fixed typo

You need to alter the InsertItem() function so that, instead of always putting the item at the end of the list, it checks to see if the item is less than the next item in the list.

    void InsertItem(ItemType x) // insert x into the list
    {
        bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;

        if (head != NULL)
        {
            location = head;
            while (location->next != NULL && x > location->data())
            {
                location = location->next;
            }
            z->next = location->next;
            location->next = z; 
            length++;
        }
        else
        {
            head = z;
            length = 1;
        }
    };  

This should work well; after all, it does in the version I wrote while trying to figure out what to recommend, though admittedly I changed an awful lot of your code in doing so. :-)

Edited 2 Years Ago by Schol-R-LEA

Comments
thnx, but i got this error when i replaced the function with yours: picture attached in reply

What are the instructions?

Implement a class SortedList as defined by the following skeleton:

#define MAX_ITEMS  10
typedef   float  ItemType;

class SortedList
{ 
       private:
    int length;
ItemType values[MAX_ITEMS];
int currentPos;
       public:
            SortedList( );  // default constructor: lenght=0, currentPos=-1
            void MakeEmpty;    // let length=0
            void InsertItem(ItemType x);   // insert x into the list     
            void DeleteItem(ItemType x);  // delete x from the list
bool IsFull( );   // test if the list is full
            int Lengthls( );   // return length
            void RetrieveItem(ItemType &x, bool &found);  // retrieve x from the list, the 
// boolean result is stored in found
    void ResetList( );  // currentPos=-1
    void GetNextItem(ItemType &x);    // get the next element from the list with 
// respect to the currentPos
};

Hint: You may use either binary or linear search in InsertItem( ), DeleteItem( ) and RetrieveItem( ).

In your main routine, the following tasks are required to complete:

Task 1: Create one instance of this class. You also need to read in data from one data file: float.dat, which contains the following numbers:
5.5
6.2
7.1
8.0
9.0
10.0
1.0
2.0
3.3
4.4

Data in float.dat contains floating numbers, which should be inserted into the object of SortedList. Note that you do not have any prior knowledge about data values in float.dat, but we assume that there are 10 elements in the data file.

Task 2: Use GetNextItem( ) to print out all the elements in the list in sorted sequence on computer screen.

Task 3: Use GetNextItem( ) to output all the elements in the list in sorted sequence onto a data file, output.dat.

Task 4: Design your test cases to demonstrate InsertItem( ), DeleteItem( ) and RetrieveItem( ) are working as expected.
..............................................................

it is like past due, but I am planning to resubmit because i just went ahead and submitted the code i had with some screenshots, but i know the sorting in order will cost me points :[ however, ill update my code with the help i am receiving; i just cant spend anymore time on this cause i have exams and other homework. Also i feel so gloomy with my eyes wide open throughout all night yesterday lol and i had a test that day too...it was so crazy.

I really am glad of all the help i recieved here though. This is like the best website i have ever used; Thanks everyone so far!

......................................
Schol-R-LEA, here is the picture of error i get 313c12dc26d8dfea54f24bff7f61cd2a

Edited 2 Years Ago by catastrophe2

actually Schol-R-LEA, i just removed paranthesis infront of data and it didnt give error. but the code didnt seem to have any impact to be better lol. i got this time even a wrong length for after the item takes 5.5, and it should be 9 like i had previously. or is length not supposed to be there? and am i having wrong stuff to test like insert 64 then deleteing it? I want the program to sort sequencially but even after adding everyone's code it still doesnt. here is the editted code so far:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define MAX_ITEMS  10

using namespace std;

typedef   float  ItemType;

float list[10];

class SortedList
{
private:
    int length;
    ItemType values[MAX_ITEMS];

    struct Node
    {
        ItemType data;
        Node* next;
    }typedef *nodeptr;

    nodeptr location;
    nodeptr trailing;
    nodeptr head;
    Node* listdata;

    int currentPos;

public:
    SortedList(){ length = 0; currentPos = -1; listdata = NULL; location = NULL; head = NULL; }; // default constructor: lenght=0, currentPos=-1

    bool IsFull() // test if the list is full
    {
        if (length < 9)
            return false;
        else
            return true;
    }; 

    void MakeEmpty()
    {
        nodeptr z;
        while (listdata != NULL)
        {
            z = listdata;
            listdata = listdata->next;
            delete z;
        }
        length = 0; // let length=0
        ;
    };    

    void InsertItem(ItemType x) // insert x into the list
    {
        bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;
        if (head != NULL)
        {
            location = head;
            while (location->next != NULL && x > location->data)
            {
                location = location->next;
            }
            z->next = location->next;
            location->next = z;
            length++;
        }
        else
        {
            head = z;
            length = 1;
        }
    };

    void DeleteItem(ItemType x) // delete x from the list
    {
        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR! Could NOT detect Deletion Value." << endl;
            delete y;
        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;
            delete y; length--;
            cout << x << " was DELETED." << endl << endl;
        }
    };  

    void Lengthls(){ cout << length << endl; }; // return length

    void RetrieveItem(ItemType x, bool &found) // retrieve x from the list, the boolean result is stored in found
    {
        location = 0;

        nodeptr y = NULL;
        location = head;
        trailing = head;
        while (location != NULL&& location->data != x)
        {
            trailing = location;
            location = location->next;
        }
        if (location == NULL)
        {
            cout << "ERROR! " << x << " NOT found!" << endl;
        }
        else
        {
            y = location;
            location = location->next;
            trailing->next = location;

            cout << endl;
            cout << x << " was FOUND." << endl;
        }
    };  

    void ResetList(){ currentPos = -1; }; // currentPos=-1

    float GetNextItem() // get the next element from the list with respect to the currentPos
    {
        currentPos++;
        float y = list[currentPos];
        return y;
    }

    void printlist()
    {
        location = head;
        while (location != NULL)
        {
            cout << location->data << endl;
            location = location->next;
        }
    }
};

int main()
{
    SortedList x;
    ifstream infile; ofstream output;
    string line;
    bool allAboutLists;

    infile.open("float.txt");

    int i = 0;
    while (infile >> list[i])
    {
        x.InsertItem(list[i]);
        ++i;
    }

    x.ResetList();

    cout << "The following is the list that's been made:" << endl << endl;

    x.InsertItem(64);
    x.printlist();
    cout << endl;
    x.DeleteItem(64);
    x.printlist();

    x.RetrieveItem(7.1, allAboutLists);
    cout << endl;

    cout << "Is the list full?: " << boolalpha << x.IsFull() << endl;
    cout << "The next item is: ";
    for (int i = 0; i < 10; i++)
    {
        cout << x.GetNextItem() << endl;
    }
    x.ResetList();

    output.open("output.txt");

    for (int f = 0; f < 10; f++)
    {
        output << x.GetNextItem() << endl;
    }
    cout << endl << "The length is: "; x.Lengthls(); cout << endl;

    system("pause");
    return 0;
}

Edited 2 Years Ago by catastrophe2

From the instructions you supplied just now, it seems to me that your list is really just an array ... of MAX_ITEMS size.

And it would also seem that you are to insert each new item in sorted order, into that array, as long as there is room.

If the above is the case ... you need to start fresh, and code for that.

// if size 0 insert in first place, ++size
// else if not full
//    find insertion index 
//    if not top position
//       move all up one to make 'hole' at index
//       insert at index
//    else insert at top
//    ++size
//  else was full

l

Edited 2 Years Ago by David W: Added comments

o well its overdue now xD, but how is it array? its from a file. I was going through my professor's notes, and he had x.compareTo function, but the program keeps saying x needs a class type or something like that. why is that? and how should i go about fixing it if i return back to fix the code?

also, how can i just add a function that makes them sorted? he asked of this but he never showed us a code that does that.

A main goal here ... seems to be ...

to learn how to code an insertion sort ...

(of an array of prefixed size = MAX_ITEMS).

It doesn't really matter where the elements come from, to test out your insert (in sorted order) function.

Of course, if you are reading in numbers from a file, you would need to test if the 'array/list' is already full, before you try to insert a new element.

The little demo below ... may get you started ?

It uses C++ overloaded [] ... (instead of a Java type next() function.)

#include <iostream>

using namespace std;

/*
Hint: You may use either binary or linear search in 
    InsertItem( ), 
    DeleteItem( ) and 
    RetrieveItem( ).

In your main routine, the following tasks are required to complete:

Task 1: Create one instance of this class. 
You also need to read in data from one data file: 
float.dat, which contains the following numbers:
5.5
6.2
7.1
8.0
9.0
10.0
1.0
2.0
3.3
4.4

Data in float.dat contains floating numbers, 
which should be inserted into the object of SortedList. 

Note that you do not have any prior knowledge about data values in float.dat, 
but we assume that there are 10 elements in the data file.

Task 2: Use GetNextItem( ) to print out all the elements 
in the list in sorted sequence on computer screen.

Task 3: Use GetNextItem( ) to output all the elements 
in the list in sorted sequence onto a data file, output.dat.

Task 4: Design your test cases to demonstrate 
    InsertItem( ), 
    DeleteItem( ) and 
    RetrieveItem( ) are working as expected.
..............................................................

it is like past due, but I am planning to resubmit 
because i just went ahead and submitted the code 
i had with some screenshots, but i know the sorting 
in order will cost me points :
[ however, ill update my code with the help i am receiving; 
i just cant spend anymore time on this cause i have exams 
and other homework. Also i feel so gloomy with my eyes wide 
open throughout all night yesterday lol and i had a test 
that day too...it was so crazy.

I really am glad of all the help i recieved here though. 
This is like the best website i have ever used; 
Thanks everyone so far!

*/

const int MAX_ITEMS = 10;


typedef float ItemType;

class SortedList
{   
private:
    int len;
    ItemType values[MAX_ITEMS];

public:
    SortedList(); // default constructor: len=0
    void empty(); // set len=0
    bool insert( const ItemType& x ); // insert x into the list
    bool erase( const ItemType& x ); // delete x from the list
    bool isFull() const;             // test if the list is full
    int size() const { return len; } // return length (in line def'n)
    int find( const ItemType& x ); // get index, -1 if not found

    ItemType& operator [] ( int i );
    const ItemType& operator [] ( int i ) const;
} ;



// definitions ... (just a few to get started)

SortedList::SortedList() : len(0) {}

void SortedList::empty() { len = 0; }

bool SortedList::insert( const ItemType& x )
{
    // if size 0 insert in first place, ++size
    // else if not full
    //    find insertion index 
    //    if not top position
    //       move all up one to make 'hole' at index
    //       insert at index
    //    else insert at top
    //    ++size
    //  else was full

    if( len )
    {
        if( !isFull() )
        {
            int j = 0;
            while( j < len && x >= values[j] )
            {
                ++j;
            }

            if( j < len ) // move all up one
            {
                for( int k = len; k >= j; -- k )
                {
                    values[k] = values[k-1]; // move up
                }
                // insert ...
                values[j]   = x;

            }
            else // we have a new top value
            {
                values[len] = x;
            }
        }
        else // was full
        {
            cout << "\nList was already full ...\n";
            return false;
        }
    }
    else values[0]= x; // was first ...

    // if reach here ...
    ++len;
    return true;

}

bool SortedList::isFull() const { return len == MAX_ITEMS; }

ItemType& SortedList::operator [] ( int i )
{
    return values[i];
}
const ItemType& SortedList::operator [] ( int i ) const
{
    return values[i];
}



// utilities ...
void print( const float ary[], int size )
{
    for( int i = 0; i < size; ++i )
        cout << ary[i] << "  ";
}

void print( const SortedList& s )
{
    for( int i = 0; i < s.size(); ++i )
        cout << s[i] << "  ";   
}


int main()
{
    float ary[] = { 5.5, 6.2, 7.1, 8.0, 9.0,
                    10.0, 1.0, 2.0, 3.3, 4.4, -1 };
    const int size = sizeof ary / sizeof ary[0];

    cout << "Unsorted array ary: \n";
    print( ary, size );
    cout << "\nof size = " << size << endl;



    SortedList sLst; // call ctor to construct an empty sLst

    // get some values into it ...
    for( int i = 0; i < size && !sLst.isFull(); ++i )
        sLst.insert( ary[i] );

    cout << "\n\nSortedList sLst: \n";
    for( int i = 0; i < sLst.size(); ++i )
    {
        cout << sLst[i] << "  "; // call overloaded []
    }


}

Edited 2 Years Ago by David W: added to code

Oh, I see what I did wrong, sorry about that. Remove the parens after data and it should work. The mistake was because I had made Node a separate class in my version, and used an accessor method to get the data from the nodes. I changed the code to reflect your version, but by force of habit added a pair of parens, thus making it look like a method call.

Edited 2 Years Ago by Schol-R-LEA

ok i worked more on this even though its too late. I just want to figure out whats the correct code? what am i missing?

here is the up-to-date code so far and errors i get:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define MAX_ITEMS  10
typedef   float  ItemType;

class SortedList
{
private:
    int length;
    ItemType values[MAX_ITEMS];
    int currentPos;
    enum RelationType { LESS, GREATER, EQUAL };

public:

    SortedList() {length = 0; currentPos = -1;}

    int getLength() {return length;}

    RelationType ComparedTo(ItemType x) 
    {
        if (length > x.getLength())
            return LESS;
        else if (length == x.getLength())
            return GREATER;
        else
            return EQUAL;
    }

    void MakeEmpty() {length = 0;}

    void InsertItem(ItemType x) 
    {   
        int first = 0, last = length --;
        bool moreToSearch = (first <= last);
        int location = 0;
        int midpoint= (first + last) / 2;

        while (moreToSearch) 
        {
            switch (x.ComparedTo(values[location])) 
            {
            case LESS:      //search in 1st half
                moreToSearch = (first <= last);
                break;
            case GREATER:
                location++;
                moreToSearch = (location < length);
                break;
            }
        }
        for (int index = length; length > location; index--) 
        {
            values[index] = values[index - 1];
        }
        values[location] = x;
        length++;
    }

    void DeleteItem(ItemType x) 
    {
        int location = 0;
        while (x.ComparedTo(values[location]) != EQUAL)
            location++;
        for (int index = location ++; index < length; index++)
            values[index --] = values[index];
        length--;
    }

    void RetrieveItem(ItemType &x, bool & found) 
    {
        int midpoint;
        int first = 0, last = length - 1;
        bool moreToSearch = (first <= last);
        found = false;
        int index = 0;
        while (moreToSearch && !found) 
        {
            midpoint = (first + last) / 2;

            switch (x.ComparedTo(values[index++])) 
            {
            case LESS:      //search in 1st half
                moreToSearch = (first <= last);
                last = midpoint - 1;
                break;
            case GREATER:   //Search in 2nd half
                first = midpoint + 1;
                moreToSearch = (first <= last);
                break;
            case EQUAL: //x has been found
                found = true;
                break;
            }
        }
    }

    int LengthIs() {return length;}

    void ResetList() {currentPos = -1;}

    bool IsFull() 
    {
        if (length < 9)
            return false;
        else
            return true;
    }

    void GetNextItem(ItemType &x) 
    {
        currentPos++;
        x = values[currentPos];
        cout << x;
    }   
};

int main()
{
    SortedList x;

    ifstream inFile; ofstream output;
    string line;
    bool allAboutLists;
    int i = 0;
    int size = 0;

    inFile.open("float.txt");

    float values[10];
    while (!inFile.eof())   // write or read data from inFile into values
    {
        inFile >> values[i];
        i++;
        size++;         // this will count how many values there are in the array
        x.InsertItem(values[i]);
        ++i;
    }

    x.ResetList();

    cout << "The following is the list that's been made:" << endl << endl;

    x.InsertItem(64);
    //x.printlist();
    cout << endl;
    x.DeleteItem(64);
    //x.printlist();

    x.RetrieveItem(7.1, allAboutLists); 
    cout << endl;

    cout << endl << "The length is: "; x.LengthIs(); cout << endl;

    cout << "Is the list full?: " << boolalpha << x.IsFull() << endl;
    cout << "The next item is: ";
    for (int i = 0; i < 10; i++)
    {
        cout << x.GetNextItem << endl;
    }
    x.ResetList();

    inFile.close();

    output.open("output.txt");

    for (int f = 0; f < 10; f++)
    {
        output << x.GetNextItem << endl;
    }

    system("pause");
    return 0;
}   

/*  ifstream inFile; ofstream output;
    int i = 0;
    int size = 0;
    inFile.open("float.txt");

    float values[10];
    while (!inFile.eof())   // write or read data from inFile into values
    {
        inFile >> values[i];
        i++;
        size++;         // this will count how many values there are in the array
    }

    GetNextItem(ItemType &x);

    inFile.close();*/

and here are the errors i get:

(25) error C2228: left of '.getLength' must have class/struct/union [they mean the x. its red lined under, same for the rest of those left of etc..]
(27) error C2228: left of '.getLength' must have class/struct/union
(44) error C2228: left of '.ComparedTo' must have class/struct/union
(66): error C2228: left of '.ComparedTo' must have class/struct/union -and also, 7.1 in main has something about refernce type mistake.

In the SortedList::ComparedTo() method, you are comparing length (the size of the SortedList) to x.getLength(), where x is an ItemType (which is a typedef of float). Since float isn't a class type, it doesn't have a getLength() method. Are you sure you didn't mean to compare x to a specific element of the list?

    RelationType ComparedTo(int pos, ItemType x) 
    {
        double value = values[pos];

        if (x < value)
            return LESS;
        else if (x > value)
            return GREATER;
        else
            return EQUAL;
    }

This may not be what you had in mind, so I'm speculating here. This is also ignoring the issues involved in exact comparisons between float values, so it may not work even now.

man this like the weirdest project so far. No one has solved it in my class, everyone just says they submitted it with errors or didnt get it to sort etc...

I understand where the program is getting at, that x must be from class and not a type float from ItemType, yet i have tried everything and added everyone's suggestions and nothing works, just makes it more complicated. I used another website as well also not good as far as getting this code fixed.

I just have a feeling that this is a syntax error. like removing a paranthesis or adding a pointer or something will fix it. just dont know what or where or how

This example may give you some ideas how your above code could be re-coded using C++ idioms (and not Java idioms) ...

// insertSortedAryList.cpp //

#include <iostream>
#include <fstream>
//#include <string>

using namespace std;


#define show 0 //set to 1 to turn ON 'showing...'//

const int MAX_ITEMS = 100; // need = at least 13 here ... //
const char* FNAME = "float.txt";
const char* FNAME_OUT = "float_sorted.txt";
/*
10.3 11.2 12.7 0.8 -3.2 11.7 -22.9 -1.1 9.9 -111.1 999 -999 0
*/


typedef float ItemType;
typedef ItemType* iter;
typedef const ItemType* const_iter;

class SortedList
{
public:

    SortedList() : length(0) {}

    int size() const  { return length; }

    void clear() { length = 0; }

    bool insert( const ItemType& x )
    {
        //cout << "length = " << length << endl;
        int i = 0;
        if( length < MAX_ITEMS )
        {
            if( length )
            {
                i = findInsertIndexBinSearch( x );
                if( i < length )
                {
                    // open up hole at index i
                    for( int hole = length; hole > i; --hole )
                    values[hole] = values[hole-1];
                }
            }
            values[i] = x;
        }
        else
        {
            cout << "\nList was FULL! NO room to insert!\n";
            return false;
        }
#if show
        cout << " at index[" << i << ']' << endl;
#endif
        ++length;
        return true;
    }

    bool erase( const ItemType& x )
    {
        bool wasDeleted = false;
        int i = foundAtIndexBinSearch( x );
        if( i >= 0 )
        {
            // copy down over item at index index i
            for( int j = i+1; j < length; ++ j )
            {
                values[j-1] = values[j];
            }
            --length;
            wasDeleted = true;
        }
        else cout << "\nNOT found!  NOT deleted!\n";

        return wasDeleted;
    }

    int find( const ItemType& x ) const
    {
        return foundAtIndexBinSearch( x );
    }

    bool isFull() const
    {
        return length == MAX_ITEMS;
    }

    void print( ostream& os ) const
    {
        for( int i = 0; i < length; ++ i )
            os << ' ' << values[i];
    }

    iter begin() { return &values[0]; }
    iter end() { return &values[length]; }

    const_iter begin() const { return &values[0]; }
    const_iter end() const { return &values[length]; }

 private:
    int length;
    ItemType values[MAX_ITEMS];

    int foundAtIndexBinSearch( ItemType val ) const
    {
        int bot = 0, mid, top = length-1;

        while( bot < top )
        {
            mid = (bot + top) / 2 ;
            if( values[mid] < val ) bot = mid+1;
            else top = mid;

        }
        if( bot < length && values[bot] == val )
            return bot;
        // else ...
        return -1;
    }
    int findInsertIndexBinSearch( ItemType val ) const
    {
        int bot = 0, mid, top = length;

        while( bot < top )
        {
            mid = (bot + top) / 2 ;
            if( values[mid] < val ) bot = mid+1;
            else top = mid;
        }
        return bot;
    }

} ;



int main()
{
    ifstream fin( FNAME );
    if( fin )
    {
        SortedList sl;
        ItemType x;
        int i = 0;
        while( i < MAX_ITEMS && fin >> x )
        {
#if show
            cout << " inserting " << x;
#endif
            sl.insert( x );
            ++i;
        }
        fin.close();

        cout << "\nAfter insert sorted size() = "
             << sl.size() << endl;

        sl.print( cout );

        cout << endl << endl;

        int foundAt = sl.find(0.8);
        if( foundAt != -1 )
            cout << 0.8 << " was found at index "
                 << foundAt << endl;

        int foundAt2 = sl.find(0.79);
        if( foundAt2 == -1 )
            cout << 0.79 << " was NOT found as returned index = "
                 << foundAt2 << endl;

        cout << "Printing to file using iter's ... \n";
        ofstream fout( FNAME_OUT );
        if( fout )
        {
            for( const_iter it = sl.begin(); it != sl.end() ; ++it )
                 fout << *it << ' ';
            fout.close();
        }
        else
            cerr << "\nThere was a problem opening file "
                 << FNAME_OUT << endl;
    }
    else
        cerr << "\nThere was a problem opening file "
             << FNAME << endl;


   cout << "\nThe following (new array_list) is not from file\n\n";

   SortedList x;
   cout << "Inserting 64 ... ";
   x.insert(64);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   cout << "\nErasing 64 ....";
   x.erase(64);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   return 0;
}

Edited 2 Years Ago by David W: changed comment

David W. dude thanks lol it worked! wish i knew this before it was due though
:[

one thing though it doesnt output to screen the list after 64 was inserted. i believe my professor would have wanted to see that.

The code is much different in aspects of coding idioms than how we are taught, I'm staring at it and making sense out of it as much as possible. I like how you added binary search and identified it as such. i had a lab and we used linear search instead of binary, lost points for that, but we had no idea how binary search is. so thanks for showing that in here.

Do you 'see' the output here ... yes it prints '64' !

 cout << "\nThe following (new array_list) "
      << "is not from file\n\n";
SortedList x;
cout << "Inserting 64 ... ";
x.insert(64);
cout << "\nx.print(cout)... \n";
x.print( cout ); /// *** what does this do ? *** ///
cout << "\nx.size() = " << x.size();
cout << "\nErasing 64 ....";
x.erase(64);
cout << "\nx.print(cout)... \n";
x.print( cout );
cout << "\nx.size() = " << x.size();

But ... one should have really inserted several values and erased several values ... printing the list at each insert and erase ... to better check to see if the code is correct ... i.e. output was ... as desired ?

Try this:

cout << "\nThe following (new array_list) is not from file\n\n";

   SortedList x;
   cout << "Inserting 64 74 70 60... ";
   x.insert(64);
   x.insert(74);
   x.insert(70);
   x.insert(60);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   cout << "\nErasing 64 ....";
   x.erase(64);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   return 0;

Edited 2 Years Ago by David W: fixed comment ... added example

o i meant that if possible the whole list of numbers with the inserted number before its deleted.

and ya, you have a good point. instead of testing one by one i can test at once several numbers.

This question has already been answered. Start a new discussion instead.