Thread: Looping through a vector of vector

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    930

    Looping through a vector of vector

    Should we looping like declaring another vector:

    Code:
    #include <vector>
    #include <iostream>
    
    using namespace std;
    
    int main() {
        vector< vector<int> > ph;
    
        vector<int> p;
        p.push_back(1);
        p.push_back(2);
        p.push_back(3);
    
        vector<int> q;
        q.push_back(10);
        q.push_back(20);
        q.push_back(30);
        q.push_back(40);
    
        ph.push_back(p);
        ph.push_back(q);
    
        for (vector< vector<int> >::size_type u = 0; u < ph.size(); u++) {
            for (vector<int>::size_type v = 0; v < ph[u].size(); v++) {
                cout << ph[u][v] << " ";
            }
            cout << endl;
        }
    }
    or is it ok just simply with an unsigned int:

    Code:
    for (unsigned u = 0; u < ph.size(); ++u) { 
       for (unsigned v = 0; v < ph[u].size(); ++v) {
        ...
       }
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Practically speaking, either is fine. If you want to be super correct, use the first.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Hell, I sometimes use plain old int, but you need to be aware of the size of the vector and know that that's a safe thing to do.

    In case you're wondering why I would ever do that, it's because of patterns like this:

    Code:
    int bestIdx = -1;
    for( int i = 0; i < (int)vec.size(); ++i )
    {
        if( MeetsSomeCondition( vec[ i ] ) && ( bestIdx < 0 || BetterThan( vec[ i ], vec[ bestIdx ] ) )
            bestIdx = i;
    }
    In other words, I want to use -1 as a placeholder for "don't have a result yet"
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    930
    Thank you very much guys!

    It was working fine with an int but i told myself better be safe than sorry.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 10:38 AM
  3. Vector class
    By Desolation in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2007, 05:44 PM
  4. Need some help/advise for Public/Private classes
    By nirali35 in forum C++ Programming
    Replies: 8
    Last Post: 09-23-2006, 12:34 PM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 01:26 AM