开发者

Adding vectors within typedef map<set,vectors>

I've a data structure as follows

typedef vector<double> v_t;
typedef set<int> s_t;
typedef map<s_t, v_t> m_t;

Lets say the map m1 that has following values :

< <1>,<1,1,1,1> >
< <2>,<2,2,2,2> >
< <3>,<3,3,3,3> >
< <4>,<4,4,4,4> >

and I've a separate vector v1 that has values like

<1,3,4>

Now what I want to do is to add the vectors the first, third and fourth vectors in the map and the result should be stored in a new map say mtot as

< <1,3,4>,<8,8,8,8> >

Here is my following try that results in a segmentation fa开发者_如何学编程ult: Any help, improvement or even your idea of implementation is greatly appreciated.

  s_t stemp,stemp1;
  v_t vtot(4); //I know the size
  typedef v_t::iterator v_it;
  typedef m_t::iterator m_it;
  // Assume I've v1 and m1 in hand

        for(v_it it(v1.begin());it != v1.end();++it)
             {
               stemp1.insert(stemp1.end(),*it);
               m_it mit = m1.find(stemp1);
               copy(mit->second.begin(),mit->second.end(),ostream_iterator<int>(cout," ")); cout << endl; // Debug not working. There is some problem with the iterator I guess
               transform(mit->second.begin(),mit->second.end(),vtot.begin(),vtot.begin(),plus<double>()); 
               stemp1.clear();
             }
             stemp.insert(v1.begin(),v1.end());
             mtot.insert(mtot.end(),make_pair(stemp,vtot));
    }

Thanks.


this line you insert not in appropriate position and not the resulting container

mtot.insert(sample.end(),make_pair(stemp,vfinal));

it can be

mtot.insert(mtot.end(),make_pair(stemp,vtot));


I presume your code works now thanks to xitx's answer.
I couldn't find significant problems in your code particularly.
Incidentally, iterator doesn't need to be specified for insert member function of set and map.
For your information, the following code worked when I tested:

int main() {
  m_t m1, mtot;
  s_t s;
  s.clear();  s.insert( 1 );  m1[ s ].assign( 4, 1 );
  s.clear();  s.insert( 2 );  m1[ s ].assign( 4, 2 );
  s.clear();  s.insert( 3 );  m1[ s ].assign( 4, 3 );
  s.clear();  s.insert( 4 );  m1[ s ].assign( 4, 4 );

  v_t  v1;
  v1.push_back( 1 );
  v1.push_back( 3 );
  v1.push_back( 4 );

  v_t vtot(4);

  for(v_it it(v1.begin());it != v1.end();++it)
  {
    s_t stemp1;
    stemp1.insert(*it);
    m_it mit = m1.find(stemp1);
    if ( mit == m1.end() ) continue;
    copy(mit->second.begin(),mit->second.end(),ostream_iterator<int>(cout," ")); cout << endl;
    transform(mit->second.begin(),mit->second.end(),vtot.begin(),vtot.begin(),plus<double>()); 
  }
  s_t stemp(v1.begin(),v1.end());
  mtot.insert(make_pair(stemp,vtot));
}

Hope this helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜