Posts

Showing posts with the label stl

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

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; } 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 e...