Vector bounds check

This is a discussion on Vector bounds check within the C++ Programming forums, part of the General Programming Boards category; How would you write a Vector template class that checks the indexes passed to the [] operator to make sure ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    18

    Vector bounds check

    How would you write a Vector template class that checks the indexes passed to the [] operator to make sure they are correct....
    Inheritance??
    I have this so far

    Code:
    template <class T> class Vector
    {
    public:
    Vector();
    Vector(int size_t n);
    ~Vector();
    
    std::vector<int> array;
     try{
     array.at(1000) = 0; 
    } 
    catch(std::out_of_range o){ 
    std::cout<<o.what()<<std::endl; 
    }

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    82
    Not sure I understand. Are you trying to derive a vector sub-class that provides bounds checking?

    If so, vector::at() already does bounds checking. It throws a std::out_of_range exception if the value is not in the range.

    Thus you use [] when you want the speed of an array, and at() when you don't want to hurt yourself (especially with calculated or arguement values which could be invalid).
    Last edited by AH_Tze; 04-06-2005 at 07:18 PM.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    18
    Yes thats what i'm trying to do...derive a template vector sub-class that provides bound checking

  4. #4
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    In your child class, provide an at() function or redefine operator[] such that you do something special (throw an exception, for example) when the inputted index is equal to or greater than size().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BN_CLICKED, change button style
    By bennyandthejets in forum Windows Programming
    Replies: 13
    Last Post: 07-05-2010, 11:42 PM
  2. How can i check a directory for certain files?
    By patrioticpar883 in forum C++ Programming
    Replies: 13
    Last Post: 02-01-2008, 04:27 PM
  3. how to check input is decimal or not?
    By kalamram in forum C Programming
    Replies: 3
    Last Post: 08-31-2007, 07:07 PM
  4. Please check this loop
    By Daesom in forum C++ Programming
    Replies: 13
    Last Post: 11-02-2006, 12:52 AM
  5. how to check for end of line in a text file
    By anooj123 in forum C++ Programming
    Replies: 6
    Last Post: 10-24-2002, 11:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21