'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;
        }
      }
c++


Solution 1:[1]

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";

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abator Abetor