Thread: Vector.size() vs iterating

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879

    Vector.size() vs iterating

    Given a std::vector<MyClass> named myVec:
    Code:
    // Loop version 1
    for (int i = 0; i < myVec.size(); ++i) {
       // Do something with myVec[i]
    }
    
    // Loop version 2
    for (std::vector<MyClass>::iterator it = myVec.begin();
          it != myVec.end(); ++it) {
       // Do something with *it
    }
    
    // Loop version 3
    for (auto &x : myVec) {
       // Do something with x
    }
    Tracing my code in a debugger I am getting size = 0, loop version 1 does not execute, and loop versions #2 and #3 enter the loop and cause an access violation.

    My suspicion is that I'm writing out of bounds somewhere and corrupting the vector's internal state, but wanted to check if you guys know of any legitimate case when this could happen.

    Thoughts?
    Last edited by Hunter2; 03-28-2014 at 12:16 AM. Reason: clearer title
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Vector Size
    By Ducky in forum C++ Programming
    Replies: 11
    Last Post: 12-10-2013, 03:43 PM
  2. Using stl's vector.size() with printf
    By manuels in forum C++ Programming
    Replies: 11
    Last Post: 08-18-2009, 07:47 PM
  3. STL question: vector size (2 dimension)
    By codeguy in forum C++ Programming
    Replies: 3
    Last Post: 02-08-2008, 05:52 AM
  4. Vector their size and declarations
    By strickey in forum C++ Programming
    Replies: 13
    Last Post: 12-29-2004, 08:45 AM
  5. getting size of a vector
    By abrege in forum C++ Programming
    Replies: 1
    Last Post: 03-31-2003, 09:48 PM