Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ vector data strucure, loop only half of elements

how to loop only half of the elements in C++ vector data structure using auto keyword

vector<string> InputFIle;

    void iterateHalf(){
        /* iterate only from begin to half of the size */
        for (auto w = InputFIle.begin(); w != InputFIle.end(); w++) {
            cout << *w << " : found " << endl;
        }
      }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to compute begin and end of your loop, i.e. first and last_exclusive.

#include <vector>
#include <numeric>
#include <iostream>

int main(){
    std::vector<int> vec(16);
    std::iota(vec.begin(), vec.end(), 0);

    size_t first = 3;
    size_t last_exclusive = 7;

    //loop using indices
    for(size_t i = first; i < last_exclusive; i++){
        const auto& w = vec[i];
        std::cout << w << " ";
    }
    std::cout << "\n";

    //loop using iterators
    for(auto iterator = vec.begin() + first; iterator != vec.begin() + last_exclusive;  ++iterator){
        const auto& w = *iterator;
        std::cout << w << " ";
    }
    std::cout << "\n";

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading