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..
The priority_queue :: value_type method is a builtin function in C++ STL which represents the type of object stored as an element in a priority_queue. It acts as a synonym for the template parameter.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With