问题
I want a vector whose elements are of the type vector::size_type
However, you cannot declare:
vector<vector::size_type> aVec;
because size_type is part of the template itself, so you have to use the type itself, I need something like:
vector<vector<T>::size_type> aVec;
but what should the T be? It's really a circular problem. :)
If vector had just used size_t as its size type (but not had a special typedef for the size_type which could vary maybe based on the type that the vector is holding), I could just do:
vector<size_t> aVec;
but, that isn't the case. I suspect there is a valid reason for it being allowed to vary, but it is making this hard by having it part of the templated vector class instead of outside of it.
Thoughts?
回答1:
std::vector<>::size_type
is static member type of the type std::size_t
so you should be safe with std::vector<std::size_t> vec
回答2:
Why don't you use vector<vector<int>::size_type> myVector;
? If you never use the type vector<int>
anywhere else, it doesn't cost anything as template instanciation is somehow lazy. You can use any other type than int
if you which.
It is very unlikely that vector<T>::size_type
will be different than vector<T'>::size_type
.
回答3:
(I am rewritting an answer here, without making any claims about the standard this time.)
You can make your best guess for the type (which can be std::size_t
or std::vector<void*>::size_type
) and check after the fact.
std::vector<std::size_t> Avec;
static_assert(std::is_same<decltype(Avec)::size_type, decltype(Avec)::value_type>(), "bad guess");
来源:https://stackoverflow.com/questions/36483817/how-do-i-declare-a-vector-of-vectorsize-type