C++ Accessing the members of a class which is the mapped_type in a std::map

c++, stdmap

Solution

`std::map` stores types internally as a `std::pair`, and `std::map::find`, returns an `iterator`. So, to access members of your class, you have to go through the `iterator`, which presents the `key_type` as `first`, and the `value_type` as `second`. Also, as others have stated, you should probably not be using `const char*` as your `key_type`. Here's a short example.

#include <string>
#include <map>
#include <iostream>

struct T
{
   T(int x, int y) : x_(x), y_(y)
   {}

   int x_, y_;
};

int main()
{
   typedef std::map<std::string, T> map_type;
   map_type m;

   m.insert(std::make_pair("0:0", T(0,0)));
   m.insert(std::make_pair("0:1", T(0,1)));
   m.insert(std::make_pair("1:1", T(1,1)));

   // find the desired item (returns an iterator to the item
   // or end() if the item doesn't exist.
   map_type::const_iterator t_0_1 = m.find("0:1");

   if(m.end() != t_0_1)
   {
      // access via the iterator (a std::pair) with 
      // key stored in first, and your contained type
      // stored in second.
      std::cout << t_0_1->second.x_ << ':' << t_0_1->second.y_ << '\n';
   }

   return 0;
}

Problem

Consider a `std::map<const char *, MyClass*>`. How do I access a member (variable or function) of the `MyClass` object pointed to by the map? ``` // assume MyClass has a string var 'fred' and a method 'ethel' std::map<const char*, MyClass*> MyMap; MyMap[ "A" ] = new MyClass; MyMap.find( "A" )->fred = "I'm a Mertz"; // <--- fails on compile MyMap.find( "A" )->second->fred = "I'm a Mertz"; // <--- also fails ``` EDIT -- per Xeo's suggestion I posted dummy code. Here is the real code. ``` // VarInfo is meta-data describing various variables, type, case, etc. std::map<std::string,VarInfo*> g_VarMap; // this is a global int main( void ) { // ........ g_VarMap["systemName"] = new VarInfo; g_VarMap.find( "systemName" ).second->setCase( VarInfo::MIXED, VarInfo::IGNORE ); // ..... } ``` errors were: ``` struct std::_Rb_tree_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, VarInfo*> >’ has no member named ‘second’ Field 'second' could not be resolved Semantic Error make: *** [src/ACT_iod.o] Error 1 C/C++ Problem Method 'setCase' could not be resolved Semantic Error – ```

Original source