Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of value_type in STL containers?

Tags:

c++

stl

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..

like image 257
InQusitive Avatar asked Jun 15 '17 15:06

InQusitive


People also ask

What is C++ Value_type?

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.


1 Answers

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;
}
like image 88
NathanOliver Avatar answered Sep 18 '22 21:09

NathanOliver