locked
MS Visual C++: Vector Subscript out of range runtime error RRS feed

  • Question

  • I having alot of trouble figuring out why my vector is out of range.  This runtime error is driving me crazy!   How do I make a vector not go out of bounds?  Can somone please explian it to me?


    file name:  StackOfIntegers.h
    ---------------------------------------------------------------------------------
    #ifndef STACKOFINTEGERS_H
    #define STACKOFINTEGERS_H

    #include <vector>
    using namespace std;

    class StackOfIntegers
    {
    private:
        vector<int> elementsVector;
        int size;

    public:
        StackOfIntegers();
        bool isEmpty();
        int peek();
        void push(int value);
        int pop();
        int getSize();
    };

    #endif




    File name:  StackOfIntegers.cpp
    -----------------------------------------------------------------------------------
    #include <vector>
    #include "StackOfIntegers.h"
    using namespace std;


    //create a default constructor
    StackOfIntegers::StackOfIntegers()
    {
        elementsVector.assign(0, 0);
    }

    bool StackOfIntegers::isEmpty()
    {
        return (elementsVector.empty());
    }

    int StackOfIntegers::peek()
    {
        return elementsVector.size() - 1;
    }

    void StackOfIntegers::push(int value)
    {
        elementsVector.push_back(value);
    }

    int StackOfIntegers::pop()
    {
        return elementsVector[--size];
    }

    int StackOfIntegers::getSize()
    {
        for (int i = 0; i < elementsVector.size(); i++)
            return elementsVector[i];
    }


    File name:  TestStackOfIntegers.cpp
    ---------------------------------------------------------------------------------------
    #include <iostream>
    #include <vector>
    #include "StackOfIntegers.h"
    using namespace std;

    int main()
    {
        //create a stack
        StackOfIntegers stack;

        //prompt user to enter number of elements
        cout << "Enter number of elements:  ";
        int numberOfElements;
        cin >> numberOfElements;

        for (int i = 0; i < numberOfElements; i++)
            stack.push(i);

        while (!stack.isEmpty())
            cout << stack.pop() << " ";

        //pause & display screen
        system("PAUSE");
        return 0;
    }

    Thursday, February 12, 2009 9:00 PM