Search code examples
c++for-loopvectorrangeauto

Trying to understand how range-based for loops work in C++


I've a program that reads from an input file an unknown amount of integers from a matrix and places them into a 2D vector. Once I have those integers inside the 2D vector I will output to another file each integers matching ASCII character. My problem is i was able to find a working double for loop that prints out 2D vectors but i'm unsure as to how the range inside the for loops work.

while(getline(in, row)){  
    int num;
    stringstream ss(row);
    vector<int> vR;
    while(ss >> num){
        vR.push_back(num);
    }
    vMain.push_back(vR);
}    

for(auto vR : vMain ){                          //<------Here
        for(auto num : vR){                     //<------Here
            if(num >= 0 && num <= 14){
                cout << " ";
                out << " ";
            }
            .
            .
            .
}

I created the while loop to take in the values of the file using a stringstream, then pushing back each row vector "vR" inside the main vector "vMain".

The for loops go through the vectors one value at a time then output the corresponding ASCII value, how exactly does the " : " range-based for loops work?


Solution

  • std::vector actually holds 3 things in addition to the actual data stored. 1) a pointer to the start of the vector. 2) a pointer to the end of the vector. 3) The size of the vector.

    Because of this, your loops "know" how many times to loop. It is (almost) equivalent to saying

    for(auto i  = vMain.begin(); i != vMain.end(); i++)
    

    Or even

    for(auto i = 0; i < vMain.size(); i++)