What is the use of value_type in STL containers?
What's the use value_type
in STL containers?
From 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 exactly is doing value_type
here? Can a variable be int
? Is this used because coders are lazy to check what type of objects are present in the vector?
As I understand it, I think I can understand allocator_type
, size_type
, difference_type
, reference
, key_type
, etc.
source to share
Yes, in your example, it's pretty easy to figure out what you want int
. Where this gets complicated is general programming. For example, if I wanted to write a generic function sum()
, I would need to know which container to iterate over and what type of its elements, so I would need 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;
}
source to share