How do I exactly know when and where to use:
Code:::size_type
How do I exactly know when and where to use:
Code:::size_type
If you have a class that derives from (or is a typedef of) a template, and you want to be able to change the template arguments without having to rewrite code that uses the class. So size_type would be a type defined by that class to act like some sort of unsigned integer, and you can probably use it as such regardless of what it is. This way your code will jive with the implementation of the class.
A good example is a type of "grid" or multidimensional array that I wrote. I started storing values as doubles, then long doubles, and then I went to some nonstandard high-precision library type. I never had to change code because everything was a grid::data_type.
Last edited by CodeMonkey; 07-28-2010 at 01:43 PM. Reason: diction
"If you tell the truth, you don't have to remember anything"
-Mark Twain
For string objects...
If you're creating a variable meant to store an index or length of a string object then it (the variable) would be of type std::string::size_type. If you're storing the return value of certain string function calls they return that type and to make things match you'd use a variable of that type to store the return value.
Many modern IDEs will indicate to you in some way what a functions return type is as you type and/or hover the mouse over a function. Your variables should be of the same type as what you're storing in them in the case of returning functions.Code:std::string name("Homer Simpson"); // Store length of string in a string::size_type variable std::string::size_type name_length = name.length(); // Store index/position of first 'm' character std::string::size_type first_m = name.find_first_of('m');
Some of your code samples have used this in an odd way, for example:
It may work, but most would have just used some kind of an int (unsigned?) in those places where the variable is simply a counter and has little (if anything) to do with a string object.Code:int main() { // The square. const string::size_type x = 10; // Amount of stars. for(unsigned int r = 0; r != x; r++) { cout << endl; string::size_type c = 0; while(c != x) { cout << "*"; ++c; } } return 0; }
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens