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

  • A+

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: