问题
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
specifically 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?
Once I am clear about this I think I will be able to understand allocator_type
,size_type
,difference_type
,reference
,key_type
etc..
回答1:
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;
}
来源:https://stackoverflow.com/questions/44571362/what-is-the-use-of-value-type-in-stl-containers