Reputation: 43
I am beginner to c++ stl language. i want to know the difference between these two codes . i asked my friend, but he is saying that both are same. can any one explain is these two are same or not. and explain why these 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;
}
Upvotes: 4
Views: 891
Reputation: 3796
size_type
is one of the common typedefs that containers define.
As it happens, sizes in STL are usually of type size_t
, which is an unsigned integral type capable of storing the maximum size of a theoretically possible object of any type.
The value is most likely compatible with an int, but the CORRECT thing to do is to always use size_type
for vector indexing. That is guaranteed to ALWAYS work (Of course the index should not be greater than vector.size()).
And if you are trying to compare unsigned and signed typed (Such as your int above), you may get unpredictable results, as signed types are converted to unsigned types.
Upvotes: 0
Reputation: 16737
vector<T>::size_type
is an implementation dependent type, which is usually size_t
. Since it isn't specified by the standard and could potentially change, you should prefer to use it when you are dealing with elements of that type. For example, the type of vector<T>::size()
returns a vector<T>::size_type
. Thus, if you are iterating over the vector
with an integral index, you would want this index to be of type vector<T>::size_type
. This will ensure that your code is easy to maintain - if you decide to use a different implementation of the standard library, your code will be consistent.
Upvotes: 6