2014-03-04 56 views
1
struct re_use_dist 
{ 
uint32_t set; 
uint32_t way; 
uint32_t rdx; 
}reusedist; 

map<pair<int, int>, int> myMap; 
myMap[make_pair(reusedist.set,reusedist.way)] = reusedist.rdx; 

我以struct的形式從文件中讀取數據並添加到地圖中。在地圖中添加多個元素<pair> C++

有沒有辦法將多個rdx添加到myMap?這種方式只存儲最後一個。

最後,我想借此連續rdx差異爲每setway

謝謝!

int difference = 0; 
    int test = 0; 
    int primary = 0; 
    int secondary = 0; 
    float average = 0; 
    vector<int> rd; 
    for(multimap<pair<int, int>,int>::iterator st=myMap.begin(), end=myMap.end();st!=end;st++) 
    { 
     std::cout<<st->first.first<<" "<< st->first.second<<" "<<st->second<<endl; 
     if(primary != st->first.first && secondary != st->first.second){ 
      vector<int>::size_type taille = rd.size(); 
      double sum = 0; 
      for(vector<int>::const_iterator i = rd.begin(); i!=rd.end(); ++i) 
      { 
       sum+=*i; 
      } 
      average = sum/taille; 
      cout<<primary<<" "<<secondary<<" "<<average<<endl; 
      primary = st->first.first; 
      secondary = st->first.second; 
      exit(0); 
     } 
     difference = st->second - test; 
     rd.push_back(difference); 
    // cout<<difference<<endl; 
     test = st->second; 
     primary = st->first.first; 
     secondary = st->first.second; 
     cout<<primary<<" "<<secondary<<endl; 
    } 
+5

如果要爲同一個鍵存儲多個值,請使用'std :: multimap'。 – nakiya

+0

正好你可以使用'std :: multimap',如果密鑰相同。 – pitnal

回答

1
std::multimap<pair<int, int>, int> myMap; 
myMap.insert(make_pair(make_pair(reusedist.set, reusedist.way), reusedist.rdx)); 

要查找的連續rdx的區別:

for (std::multimap<pair<int, int>, int>::const_iterator i = myMap.begin(); i != myMap.end();) { 
    pair<int, int> key = i->first; 
    std::multimap<pair<int, int>, int>::const_iterator rbound = myMap.upper_bound(key); 
    std::multimap<pair<int, int>, int>::const_iterator j = i, k = i; 
    ++k; 
    for (; k != rbound; j = k, ++k) { 
     int difference = k->second - j->second; 
    } 
    i = rbound; 
} 

另一種方法:map<pair<int, int>, vector<int> >

map<pair<int, int>, vector<int> > myMap; 
myMap[make_pair(reusedist.set, reusedist.way)].push_back(reusedist.rdx); 

for (map<pair<int, int>, vector<int> >::const_iterator i = myMap.begin(); i != myMap.end(); ++i) { 
    pair<int, int> key = i->first; 
    const vector<int> &rdxes = i->second; 
    for (vector<int>::const_iterator j = rdxes.begin(); j+1 != rdxes.end(); ++j) { 
     int difference = *(j+1) - *j; 
    } 
} 
+0

任何想法如何找到連續rdx的區別? – pistal

+0

'difference = st-> second - test;' 'cout << difference << endl;' 'test = st-> second;' 這是非常原始的,不會幫助我爲更多的個人對平均差。 – pistal

+0

@pistal編輯瞭如何對'set'和'way'給出'rdx'的連續差異。 – timrau