Unsigned int or size_t?

Hi,

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 unsigned int to replace size_t? What should we use when there is a nested loop (when I need to control more in the loop with const int a) like

1
2
3
for(size_t i=0; i<vector.size(); i++) {
   if(i<a) {
      ......

Actually here size_t type cannot work. So what is exactly the rule for these kinds of usage, when use int, unsigned int, size_t...?

Thanks in advance.
Could anyone help to explain this, please?
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)
    //.... 
Last edited on
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using MyVec_t = std::vector<int>;
MyVec_t MyVec;
//...
for(MyVec_t::size_type i {0}; i < MyVec.size(); ++i)
{
    /*code*/
}
//...
for(MyVec_t::/*const_*/iterator it {MyVec.begin()}; it != MyVec.end(); ++it)
{
    /*code*/
}
//...
for(auto it {MyVec.begin()}; it != MyVec.end(); ++it)
{
    /*code*/
}
//...
//#include <algorithm>
std::for_each(MyVec.begin(), MyVec.end(), [/**/](MyVec_t::value_type /*const*/&elem)
{
    /*code*/
});
Last edited on

@L B


You forgot the for statement based on range

for ( auto x : MyVec ) /* some statement */;
It doesn't let you decide the range, which is what I thought the OP needed index-based iteration for.
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?

Thanks for your explanations!

Last edited on
All objects created on the stack are destructed at the end of their scope.
Topic archived. No new replies allowed.