C++ creating and printing an STL list (instead of a linked list)

Oct 29, 2016 at 9:32pm
So right now I'm trying to implement a list using STL but I'm stuck at what to do for the print function (so I'm not sure how to test if the insertFront function works properly). I've searched for solutions but I'm having a difficult time understanding. I'm having some trouble using iterators in this implementation as well.

All the examples I've seen are implemented in a single file without needing function calls so this is extremely confusing for me.

Right now I'm getting an access violation error and am not sure how to properly initialize the pointer (assuming it's not done the same way as in an actual linked list with ptr = nullptr or something).

The function getNumOfElem() was already there as a working example. The only stuff I added are the functions other than that one.

Here's my code:

AnyList.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class AnyList
{
public:

    AnyList();

    int getNumOfElem() const;

    void insertFront(int data);
    void forwardPrint();

private:
    list<int> *ptr; 
};


AnyList.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
AnyList::AnyList() 
{

}

int AnyList::getNumOfElem() const
{
    return static_cast<int>(ptr->size());
}

void AnyList::insertFront(int data)
{
    ptr->push_front(data);
}

void AnyList::forwardPrint()
{
    list<int>::const_iterator i;
    for (i = ptr->begin(); i != ptr->end(); ++i)
    {
        cout << *i << " ";
        cout << endl;
    }
}


Main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    AnyList list1, list2;

    list1.insertFront(10);
    list1.insertFront(11);
    list1.insertFront(12);
    list1.insertFront(13);
    list1.insertFront(14);


    cout << "\nList 1: ";
    list1.forwardPrint();
}


Any insight would be greatly appreciated, thanks!

Edit: Gonna include the instructions so there's no confusion as to what I'm supposed to be trying to accomplish.

http://imgur.com/a/ecPHc
Last edited on Oct 29, 2016 at 9:57pm
Oct 30, 2016 at 12:00am
The ptr member of AnyList is never assigned or initialized to any value, so it points to some random place in memory. You are trying to treat that random place as if it is a std::list. It isn't. Don't do that.
Oct 30, 2016 at 12:10am
Thanks! Changed it to

ptr = new list<int>();

and it seems to work now. I just had no idea what it was supposed to point to.
Oct 30, 2016 at 5:48am
OP: forwardPrint() should also be declared const
Topic archived. No new replies allowed.