What is the difference between using a vector <int> :: size_type and a normal integer?

I am starting with C ++ stl language. I want to know the difference between these two codes. - I asked my friend, but he says that they are both the same. can anyone explain if these two are the same or not. and explain why they are different

#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<double> student_marks(20);
    for (vector<double>::size_type i = 0; i < 20; i++){
        cout << "Enter marks for student #" << i+1
             << ": " << flush;
        cin >> student_marks[i];
    }
    return 0;
}

      

and

#include<iostream>
#include<vector>
using namespace std;
int main(){
    vector<double> student_marks(20);
    for (int i = 0; i < 20; i++)
    {
        cout << "Enter marks for student #" << i+1
             << ": " << flush;
        cin >> student_marks[i];
    }
    return 0;
}

      

+3


source to share


2 answers


vector<T>::size_type

is an implementation-dependent type, usually size_t

. Since it is not specified by the standard and could potentially change, you should use it when dealing with elements of this type. For example, the type vector<T>::size()

returns a vector<T>::size_type

. Thus, if you are iterating vector

with an integral index, you want that index to be of type vector<T>::size_type

. This ensures that your code is easy to maintain - if you choose to use a different implementation of the standard library, your code will be consistent.



+6


source


size_type

is one of the common typedefs that define containers. As is the case, dimensions in STL are usually of a type size_t

, which is an unsigned integral type capable of holding the maximum size of any theoretically possible object of any type.



The value is most likely int compatible, but the CORRECT thing to do is always use size_type

for vector indexing. This is guaranteed to ALWAYS work (of course, the index should not be larger than vector.size ()).
And if you are trying to compare unsigned and signed types (like your int above), you can get unpredictable results, since signed types are converted to unsigned types.

0


source







All Articles