[Solved] C++ vector data strucure, loop only half of elements


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

}

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