Dear guys,
I come across a book that declare something like queue<char>::size_type mismatches = 0;
I don't quite get it, why not just say int mismatches = 0? Why use such strange syntax queue<char>::size_type? What advantage does such a variable type provides over a simple int?
And by the way, I think I have come across another type which is size_t as well. Can anyone tell me what exactly are the difference among the three? Namely size_type, size_t, int (and perhaps unsigned int too)?
Many thanks.
Regards,
Bosco
queue<char>::size_type is a class-dependent type. For example it can be an unsigned type. So when you will compare it with int you can get unpredictable result because a negative integer value will be converted to unsigned type.
Usually a compiler issue a warning when you are trying to do such conparisions.
Also int type can be "shorter" then queue<char>::size_type and it will be unable to store all values of queue<char>::size_type.
size_t is a standard type name. It is not a class-dependent type. operator sizeof has return type of size_t.
So size_t is unsigned arithmetic type and is defined with the typedef specifier for some fundamental type. Which fundamental type will be selected is implementation-dependent.
queue<char>::size_type is a class-dependent type. It may be any type.
int is a signed integer fundamental type of C/C++.
The Standard Template Library contains a set of containers and a set of algorithms. In an attempt to reduce the number of actual functions, it uses common means of accessing the containers.
So containers can be traversed with these things called iterators, and define a set of common local typedefs that represent interesting things. In this way, a single function (algorithm) can work on a range of containers using this common stuff.
For example, consider the function for_each() that applies a functor to each element of the container passed in, there isn't a different implementation for list, vector, set and so on; there's just one implementation that uses the common stuff in the containers.
size_type is one of the common typedefs that containers define.
As it happens, sizes in STL are of type size_t, which is typically an unsigned int, not an int.
Well... Can I just replace queue<char>::size_type with size_t whenever I need to use the former then? Is there something that queue<char>::size_type can do but size_t cannot, or vice versa?
sorry... one extra question, is size_type standard? or do I need to define every time with a statement like this: typedef std::size_t size_type; ?? I see that in the book Data Structures & Other Objects Using C++ by Michael Main and Walter Savitch they do it that way