I know that to run a for loop we can use int to control like for(int i=0; i<x; i++). But when x is a size function we have to use size_t type like for(size_t i=0; i<vector.size(); i++).
Can we use unsignedint to replace size_t? What should we use when there is a nested loop (when I need to control more in the loop with constint a) like
The loop will work with 'i' as an int or unsigned int perfectly fine in this scenario, but might generate compiler warnings.
The main idea is, you want to make the type of 'i' match the type of whatever you're comparing it with. So 'i' should have the same type as 'vector.size()'.
In this case, the proper way to loop is use vector<T>::size_type:
1 2
for(vector<int>::size_type i = 0; i < vector.size(); ++i)
//....
It is not necessary that size_t is defined as unsigned int. According to the C++ Standard
6 The type size_t is an implementation-deļ¬ned unsigned integer type that is large enough to contain the size in bytes of any object.
And moreover method size of the template class vector may have a different type compared to size_t. So it is better to use std::vector<T>::size_type instead of size_t
Thanks guys for all your explanations... Now I think I get something with this.
Two more questions: if we define an iterator in a "for" loop, when the loop is finished, the iterator is destroyed automatically. What about if we define an iterator in a function? Shall we destroy is after usage in the function? or we can just leave it in the function and when the function is finished the iterator will be destroyed automatically?