Thread: Nested for loop & vector issue

  1. #1
    Registered User
    Join Date
    Apr 2008
    Location
    Australia
    Posts
    55

    Nested for loop & vector issue

    Hi,

    I can't seem to understand why this is not working as expected. The output from the two "couts" are different. Can someone please explain why?

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    
    int main()
    {
      vector<int> vIntA, vIntB;
     
    
      for(int a =0; a<6;a++)
      {
          for(int b=0; b< 5; b++ )
           {
            vIntA.push_back(a);
            vIntB.push_back(b);
            cout << "a: " << a << ", b: " << b << "\n";
            }
       }
    
      for(int a =0; a<6;a++)
      {
          for(int b=0; b< 5; b++ )
             cout << "a: " << a   ", vIntA: " << vIntA.at(a) << ", vIntB: " << vIntB.at(b) << "\n";
      }
    
       return 0;
    }
    1st cout:
    -a & b work as intended.
    2nd cout:
    -a & b is ok, as is vIntB. But vIntA is incorrect, mostly with zeros until it accesses 5th element where it's 1's.

    What am I missing here?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > vIntA.push_back(a);
    How many a=0 copies get pushed onto the vector?
    How many a=1 ?

    You're not printing exactly what you're pushing.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    71
    In the first for loops, 'a' loops onces, and 'b' loops 5 times. Then again goes to 'a'.

    When enters in the 'b' loop, it will loop over and over until is done. Then it will go back to 'a' loop, where will meet 'b' loop again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested while loop inside for loop
    By Sonny in forum C Programming
    Replies: 71
    Last Post: 07-31-2011, 08:38 PM
  2. Recusively nested vector template: How to?
    By User Name: in forum C++ Programming
    Replies: 7
    Last Post: 02-08-2011, 06:07 PM
  3. Nested For Loop
    By yacek in forum C Programming
    Replies: 3
    Last Post: 12-07-2010, 10:58 PM
  4. is there easy way to clear nested vector?
    By timchen in forum C++ Programming
    Replies: 1
    Last Post: 12-26-2007, 10:18 PM
  5. nested switch issue
    By fsu_altek in forum C Programming
    Replies: 3
    Last Post: 02-15-2006, 10:29 PM