C++ – Purpose of Declaring vector::size_type Variable

c++stdtypesvector

I think this is a very basic question but I couldn't just figure it out.

I was used to using arrays in C++ but I'm now starting to learn vectors.
I was making a test code, and I came across a question.

First of all, here's the code I made:

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main(){
  vector<double> score(10);

  for(vector<double>::size_type i=0;i<20;i++) {
    cout<<"Enter marks for student #"<<i+1<<":"<<flush;
    cin>>score[i];
  }

  double total = accumulate(score.begin(), score.end(),0);

  cout<<"Total score:"<<total<<endl<<"Average score:"<<total/score.size()<<flush;

  return 0;
}

In the for sentence in line #9, I am declaring i as a vector<double>::size_type type (because I was told to do so).
I tested the code with the type said above replaced with an int, and it worked perfectly fine.
Why is vector<double>::size_type preferred compared to int?

Best Answer

size_type is guaranteed to be large enough for the largest supported vector size, vector::max_size(). int is not: on many common platforms, int has 32 bits, while max_size() is considerably larger than 231.

If you know the size is (and will always be) a small number like 20, then you can get away with using int or any other integer type instead of size_type. If you were to change the program, for example to read the size from the input, then it would go horribly wrong if that value were larger than INT_MAX; while using size_type, it would continue working for any value up to max_size(), which you can easily test for.

Related Question