Reputation: 5859
What's the use of value_type
in STL containers?
From the MSDN:
// vector_value_type.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
int main( )
{
using namespace std;
vector<int>::value_type AnInt;
AnInt = 44;
cout << AnInt << endl;
}
I don't understand what does value_type
achieve here?
The variable could be an int
as well? Is it used because the coders are lazy to check what's the type of objects present in the vector?
I think these are also similar to it allocator_type
,size_type
,difference_type
,reference
,key_type
etc..
Upvotes: 28
Views: 29674
Reputation: 180955
Yes, in your example, it is pretty easy to know that you need an int
. Where it gets complicated is generic programming. For example, if I wanted to write a generic sum()
function, I would need it to know what kind of container to iterate and what type its elements are, so I would need to have something like this:
template<typename Container>
typename Container::value_type sum(const Container& cont)
{
typename Container::value_type total = 0;
for (const auto& e : cont)
total += e;
return total;
}
Upvotes: 48