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;
}
}
CodePudding user response:
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";
}