for loops

I am trying to fully understand for loops in c/c++. The more i read, the more i find of ways to write for loops. Its seems complicated, with all the ways to write a for loop. And remembering each one, and each one's syntax. First of all, are there any more ways to write a for loop that is not included?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>

int main(){
    std::vector<int> v = {1,2,3,4,5};
    
    for (std::vector<int>::iterator it = v.begin(); it != v.end(); it++){
        std::cout << *it << ' ';
    }
    std::cout << std::endl;
    for (int i=0; i<v.size(); i++){
        std::cout << v[i] << ' ';
    }
    std::cout << std::endl;
    for (auto it = v.begin(); it != v.end(); it++){
        std::cout << *it << ' ';
    }
    std::cout << std::endl;
    for (auto i: v){
        std::cout << i << ' ';
    }
    
}
Last edited on
For example you can write the folloiwng way ( without testing)

1
2
3
4
for ( std::vector<int>::size_type i = 0; std::vector<int>::size_type n = v.size() - i; i++ )
{
   std::cout << v[i] << ' ';
}
Last edited on
what is ::size_type mean?
based on yours i also added auto to replace std::vector<int>::size_type. Is that the purpose of auto, is to replace syntax for easier reading?
1
2
3
	for ( auto i = 0; auto n = v.size() - i; i++ ){
	   std::cout << v[i] << ' ';
	}
Yes you can substitute for auto. In any case expression v.size() - i has type std::vector<int>::size_type. though i has type int:)

Last edited on
Topic archived. No new replies allowed.