I am new to C . I found that to see a variable's type, I can use typeid().name() on library "typeinfo". But when I implement this function on map data structure, I got this output
Type of itr is : St17_Rb_tree_iteratorISt4pairIKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiEE
What is that mean ? Actually I want to know what is type of itr which is the iterator of map in the code section.
#include <iostream>
#include <string>
#include <iterator>
#include <map>
#include <typeinfo>
using namespace std;
int main()
{
map <string, int> map1;
map1.insert({"A",1});
auto itr = map1.begin(); // Iterator is created by auto
for (itr; itr != map1.end(); itr )
{
cout<<itr->first<<" "<<itr->second<<"\n";
}
cout<<"Type of itr is : "<<typeid(itr).name();
return 0;
}
CodePudding user response:
I want to know what is type of itr which is the iterator of map in the code section?
The type of map1.begin()
is
std::map<std::string, int>::iterator
You can test it via
#include <type_traits> // std::is_same_v
static_assert(std::is_same_v<
decltype(map1.begin()), std::map<std::string, int>::iterator>
, "are not same");
i.e. Alternative to auto
keyword and the above (i.e std::map<std::string, int>::iterator
), you could use decltype(map1.begin())
as well.
St17_Rb_tree_iteratorISt4pairIKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiEE
What is that mean ?
It's the name of the type as per compiler implementations. From std::type_info::name
Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.
Therefore, it could vary compiler-to-compiler, and can not argue this will look the same always.
For instance, have a look into the type of map1.begin()
in different compiler here: https://gcc.godbolt.org/z/ProxxaxfW
CodePudding user response:
#include <iostream>
#include <string>
#include <iterator>
#include <map>
#include <typeinfo>
using namespace std;
int main()
{
map <string, int> map1;
map1.insert({"A",1});
auto itr = map1.begin(); // Iterator is created by auto
for (itr; itr != map1.end(); itr )
{
cout<<itr->first<<" "<<itr->second<<"\n";
}
cout<<"Type of itr is : "<<typeid(itr).name();
return 0;
}