Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we print out the value_type of a C++ STL container?

Tags:

c++

stl

I know that STL containers have a value_type parameter and I've seen how it can be used to declare a type of a variable like:

vector<int>::value_type foo;

But can we just print this value_type to a console?

I want to see "string" in this example:

int main() {
    vector<string> v = {"apple", "facebook", "microsoft", "google"};
    cout << v << endl;
    cout << v.value_type << endl;
    return 0;
}
like image 215
Niakrais Avatar asked Sep 03 '18 09:09

Niakrais


People also ask

What is Value_type C++?

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.

What is an STL container C++?

This article focuses on the C++ STL container set. STL containers are objects that can store multiple elements, manage any storage required for the elements, and offer member functions we can use to access them. A container may allow elements of either the same type or different types to be stored in it.


1 Answers

X::value_type is no different from any other type alias (aka typedef) in this regard — C++ has no native way of converting a type to its source code string representation (not the least because that could be ambiguous). What you can do is use std::type_info::name:

cout << typeid(decltype(v)::value_type).name() << endl;

The resulting text is compiler dependent (and not even guaranteed to be easily human readable). It will be consistent within the same build of a program, but you cannot expect it to be the same across different compilers. In other words, it's useful for debugging, but cannot reliably be used in a persistent fashion.

like image 197
Angew is no longer proud of SO Avatar answered Sep 20 '22 22:09

Angew is no longer proud of SO