vector<int>::size_type in C++

C++VectorSize Type

C++ Problem Overview


What is meant by this C++ statement?

vector<int>::size_type x;

And, what is the use of the scope operator :: here? In other words, how do we read this statement in English?

For example, for X::x(){...}, we say that x() is a member function of class X.

C++ Solutions


Solution 1 - C++

size_type is a (static) member type of the type vector<int>. Usually, it is a typedef for std::size_t, which itself is usually a typedef for unsigned int or unsigned long long.

Solution 2 - C++

I would read it as "declare x as a variable of a type suitable for holding the size of a vector". The vector defines its own type for its length, and it's always cleanest to use that if possible, rather than "guessing" and using int, unsigned int, long, unsigned long or size_t etc directly as you'd otherwise need to do.

Solution 3 - C++

vector is a template

so the vector type templated with int has a member typedef called size_type. x is defined as a variable of that type.

Solution 4 - C++

> Different implementations use different types to represent sizes, so > we cannot write the appropriate type directly and remain > implementation-independent. For that reason, it is good programming > practice to use the size_type that the library defines to represent > container sizes.

- Accelerated C++ by Andrew Koenig and Barbara E. Moo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimplicityView Question on Stackoverflow
Solution 1 - C++fredoverflowView Answer on Stackoverflow
Solution 2 - C++unwindView Answer on Stackoverflow
Solution 3 - C++T33CView Answer on Stackoverflow
Solution 4 - C++PuddleView Answer on Stackoverflow