开发者

Access to map data

开发者 https://www.devze.com 2023-02-10 22:20 出处:网络
I have a complex map that defined typedef short short1 typedef short short2 typedefmap<short1,short2> data_list;

I have a complex map that defined

 typedef short short1
 typedef short short2
 typedef  map<short1,short2> data_list;
 typedef  map<string,data_list> table_list;

I have a class that fill table_list

class GroupingClass
{
    table_list m_table_list;
    string Buildkey(OD e1){
       string ostring;
       ostring+=string(e1.m_Date,sizeof(Date));
       ostring+=string(e1.m_CT,sizeof(CT));
       ostring+=string(e1.m_PT,sizeof(PT));
       return ostring;
   }
   void operator() (const  map<short1,short2>::value_type& myPair) {

       OD e1=myPair.second;
       string key=Buildkey(e1);
       m_table_list[key][e1.m_short1]=e1.m_short2;
   }

   operator table_list() {
    return m_table_list;
   }
};

and I use it by

  table_list TL2    
  GroupingClass gc;
  TL2=for_each(mapOD.begin(), mapOD.end(), gc);

but when I try to access to internal map I have problems for example

 data_list tmp;
 tmp=TL2["AAAA"];
 short i=tmp[1]; //I dont update i variable

and when debug it, I see code try add new value to map.then when tmp var is const this cause to a error

but if i use a loop by itrator th开发者_JAVA百科is work properly why this no work at first way thanks herzl


std::map<Key,Value>::operator[](Key const& k) will look for key k. If it's not found, it will insert a new Value() and return a reference to that. This is a modifying operation. Therefore, operator[] is non-const.


The code does not make sense. What is OD? myPair.second would be short in operator() but then you do e1.m_short2 which does not make any sense.

Your likely bug is that for_each takes its 3rd parameter by value which means it is going to make copies of that map and probably you will lose the changes.

You can force for_each to take the 3rd value by reference either by specifying the template parameter directly or by wrapping in boost::ref. However you would do far better to make your functor take the map it is building by reference in its constructor rather than have an instance of a map.

class GroupingClass
{
    table_list & m_table_list;
    string Buildkey(OD e1)
    {
       string ostring;
       ostring+=string(e1.m_Date,sizeof(Date));
       ostring+=string(e1.m_CT,sizeof(CT));
       ostring+=string(e1.m_PT,sizeof(PT));
       return ostring;
   }
   public:
   explicit GroupingClass( table_list & the_table_list ) :
     m_table_list( the_table_list )
   {
   }

   void operator() (const  map<short1,short2>::value_type& myPair) const
   {

       OD e1(myPair.first); // probably what you meant
       string key=Buildkey(e1);
       m_table_list[key][e1.m_short1]=e1.m_short2;
  // did you mean m_table_list[key][myPair.first] = myPair.second; ?
   }
};

and use it by

table_list TL2;
for_each(mapOD.begin(), mapOD.end(), GroupingClass(TL2));
0

精彩评论

暂无评论...
验证码 换一张
取 消