Thread: Vector subscript out of error. Please help!

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    32

    Vector subscript out of error. Please help!

    Hi,

    I'm writing this program to calculate quartiles. The error message is that the vector subscript is out of range; however, I have not been able to pinpoint where it is. Could you please help? This program is Exercise 3.2 from Accelerated C++. Thank you very much!

    PHP Code:
    /*
        Write a program to compute & print the quartiles of a set of integers
        Method used in this program:
        (1) Use the median to divide the ordered data set into two halves. 
            Do not include the median into the halves.
        (2) The lower quartile value is the median of the lower half of the data. 
            The upper quartile value is the median of the upper half of the data.
    */

    #include <algorithm>
    #include <iomanip>
    #include <ios>
    #include <iostream>
    #include <string>
    #include <vector>

    using std::cin;                using std::sort;
    using std::cout;            using std::streamsize;
    using std::endl;            using std::string;
    using std::setprecision;    using std::vector;

    int main()
    {
        
    // ask for a set of integer values
        
    cout << "Enter some integer values: ";
        
    vector<intnumbers;
        
    int x;
        while (
    cin >> x)
            
    numbers.push_back(x);

        
    // check that the user entered some integer values
        
    typedef vector<int>::size_type vector_size;
        
    vector_size size numbers.size();
        if (
    size == 0) {
            
    cout << endl << "You must enter at least one integer value. "
                         
    << "Please try again." << endl;
            return 
    1;
        }
        
        
    // sort the numbers
        
    sort(numbers.begin(), numbers.end());
        
        
    // median, 1st quartile, 3rd quartile, min, max
        
    vector_size mid size 2;
        
    double minmaxmedianlquartileuquartile;
        
    min numbers[0]; 
        
    max numbers[size-1];
        
    median size == ? (numbers[mid] + numbers[mid-1])/2.0 numbers[mid];
        
        
    // break the vector into halves
        
    vector<intnumbers1// vector containing lower quartile
        
    vector<intnumbers2// vector containing upper quartile
        
    if (size == 0) {
            for (
    int i 0mid-1; ++i) {
                
    numbers1.push_back(numbers[i]);
            }
            for (
    int j mid+1<= size; ++j) {
                
    numbers2.push_back(numbers[j]);
            }
        }
        else {
            for (
    int i 0mid; ++i) {
                
    numbers1.push_back(numbers[i]);
            }
            for (
    int j mid+1<= size; ++j) {
                
    numbers2.push_back(numbers[j]);
            }
        }
        
    // sort the two vectors
        
    sort(numbers1.begin(), numbers1.end());
        
    sort(numbers2.begin(), numbers2.end());

        
    vector_size size1 numbers1.size(); 
        
    vector_size mid1 size1 2;
        
    vector_size size2 numbers2.size();
        
    vector_size mid2 size2 2;
        
    lquartile size1 == ? (numbers1[mid1] + numbers1[mid1-1])/numbers1[mid1];
        
    uquartile size2 == ? (numbers2[mid2] + numbers2[mid2-1])/numbers2[mid2];

        
    // print the results
        
    cout << "Median = " << median << endl;
        
    cout << "Min = " << min << endl;
        
    cout << "Max = " << max << endl;
        
    cout << "Lower quartile = " << lquartile << endl;
        
    cout << "Upper quartile = " << uquartile << endl;

        return 
    0;


  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    A subscript is this:
    Code:
    numbers1[mid1]
    I don't get any error when I compile and run this:

    [root~/C++] ./a.out
    Enter some integer values: 1 10 300
    Median = 10
    Min = 1
    Max = 300
    Lower quartile = 1
    Upper quartile = 150

    ps. how about:
    Code:
    using namespace std;
    in place of:
    Code:
    using std::cin;                using std::sort;
    using std::cout;            using std::streamsize;
    using std::endl;            using std::string;
    using std::setprecision;    using std::vector;
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Know how to run code through the debugger? It would allow you to step through the code and find out where exactly the problem happens:
    Code:
    typedef vector<int>::size_type vector_size;
    vector_size size = numbers.size(); 
    
    ...
    
    if (size % 2 == 0) {
        for (int i = 0; i < mid-1; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    else {
        for (int i = 0; i < mid; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    I've highlighted the problem areas.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Oh yeah. Size() returns the number of elements in the vector, but the first subscript is 0, not 1, so they are numbered 0 to size-1.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Dec 2009
    Posts
    32
    Thank you very much. The code now runs without errors after I removed "=", as you suggested...

    Quote Originally Posted by hk_mp5kpdw View Post
    Know how to run code through the debugger? It would allow you to step through the code and find out where exactly the problem happens:
    Code:
    typedef vector<int>::size_type vector_size;
    vector_size size = numbers.size(); 
    
    ...
    
    if (size % 2 == 0) {
        for (int i = 0; i < mid-1; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    else {
        for (int i = 0; i < mid; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    I've highlighted the problem areas.

  6. #6
    Registered User
    Join Date
    Dec 2009
    Posts
    32
    Hi hk_mp5pdw, how can I run the code through the debugger? I don't get that. Can you show me how? The errors only come when I run the program, and it just give general errors, not where it is...


    Quote Originally Posted by hk_mp5kpdw View Post
    Know how to run code through the debugger? It would allow you to step through the code and find out where exactly the problem happens:
    Code:
    typedef vector<int>::size_type vector_size;
    vector_size size = numbers.size(); 
    
    ...
    
    if (size % 2 == 0) {
        for (int i = 0; i < mid-1; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    else {
        for (int i = 0; i < mid; ++i) {
            numbers1.push_back(numbers[i]);
        }
        for (int j = mid+1; j <= size; ++j) {
            numbers2.push_back(numbers[j]);
        }
    }
    I've highlighted the problem areas.

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by pantera View Post
    Hi hk_mp5pdw, how can I run the code through the debugger? I don't get that. Can you show me how? The errors only come when I run the program, and it just give general errors, not where it is...
    What compiler/IDE are you working with?
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    If you're on linux you can use gdb, here's how to find a segfault:

    getting a segfault using pointers

    This works the same with g++ as gcc. You error is not a segfault, so one way to go is use "breakpoints", and "print" to show the value of variables. There is a graphical frontend to gdb too, but it's easiest to learn and use, the first few times at least, on the command line.

    http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html

    Most relevant here are section 4 and section 2.
    Last edited by MK27; 04-28-2010 at 06:16 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User
    Join Date
    Dec 2009
    Posts
    32
    Hi, I'm using Visual C++ Express 2008 at school, and Terminal at home (Mac OS). Thanks a lot

    Quote Originally Posted by hk_mp5kpdw View Post
    What compiler/IDE are you working with?

  10. #10
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Don't know about the Mac one and I only have Visual Studio 2005 on my machine but I'd think 2008 isn't too different.

    To start make sure you've got yourself a debug (not release) build of your application. In the source code window go to some line before you think the error occurs and click somewhere in that source window so your cursor is on the line in question. Press F9 and a little red icon pops up on the left of the source code window (it might look like a circle or a stop sign). This is a break point and execution of your code when running it through the debugger will always stop at these places (you can put several of them throughout the code if you wish). With your code I put mine after the code that gets the user input and after the sorting, somewhere around the lines where you are calculating min/max/median looked good to me.

    You can then press F5 to run your application in the debugger. Your console window will pop up asking for the values which you can enter as you normally would. After entering the values, the console window will either move to the background and the IDE application will move to the foreground or the IDE's icon in the taskbar will flash indicating that you should switch to that application by clicking on it. In the IDE window, an icon (an arrow) indicating the current line will be displayed where you placed the (first) break point, this indicates your current line number in the execution of your code through the debugger.

    Other areas in the IDE's application window should be visible to you titled "Locals" and "Watch 1". The "Locals" window shows the current values stored in all the local variables visible in your current scope (the variable visible to you at that point in the execution of your code). The "Watch 1" window is where you can enter the name of a specific variable you wish to keep track of and can be more convenient if there are a large number of locals you don't care to see the values of. In debugging the above problem I entered "j" and "size" into the Watch windows to keep easy track of their values. Don't worry if one of them says "Error symbol "X" not found"... that simply means the variable isn't currently in scope yet.

    From this point you should press F10 to step through the code line by line. You can see the values of any variables that change as a result of the last line executed appear in red in the Locals/Watch windows. In the version of the code posted above, press the F10 until you are in the "j" for-loop pushing numbers into the "numbers2" vector. Eventually, just before your program crashes, you'll notice that "j" become equal to "size" in your Watch window and as the push_back gets executed by pressing F10 one last time, you should see the program crash at that point. Click on "Abort" in the window that pops up and you should be back in the IDE's window with your program now kicked out of debugging mode due to the crash.

    As MK27 and I indicated in our posts above, vectors are zero-based so the range of valid indexes goes from 0 up to N-1 for an N element vector. "j" being equal to "size" is something that should not happen and indicates you are trying to access an element that is not there during the push_back call. At this point you would hopefully have a good idea of what happened to cause the crash and be able to correct your code and make another attempt at running it.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed