2014-01-19 18 views
0

使用make_pair后之后,我以这种形式得到了一些对即pairToCount分组一些对使用make_pair

(件1件2)=频繁#在DB:

(1 2) = 1 
(1 3) = 1 
(1 4) = 1 
(2 3) = 2 
(2 4) = 3 
(2 5) = 1 
(3 4) = 2 
(5 4) = 1 

我想对每个数字(1,2,3,4,5)做如下操作:

首先,检查每一对数字1 ==>然后总结其频率,例如: 1存在于以下对中:(1 2),(1 3),(1 4)==>频率总和= 1 + 1 + 1 = 3

做同样为2,3,4,5-

2是(1 2),(2 3),(2 4),(2 5)==>的存在总和频繁为= 1 + 2 + 3 + 1 = 7

3是在(1 3),(2 3),(3 4)==>有频繁的总和= 1 + 2 + 2 = 5

等。这是我写的代码。

int sum = 0; 
    int found; 
    for (const auto& p1 : pairToCount) 
    { 
     int r = p1.first.first; 
     std::cout << " (" << r; 

     for (const auto& p2 : pairToCount) 
     { 
      if (r == p2.first.first) 
      { 
       sum += p2.second; 
       found = p2.first.second; 
      } 

      else if (r == p2.first.second) 
      { 
       sum += p2.second; 
       found = p2.first.first; 
      } 
      else 
       exit; 
      std::cout << "," << found ; 
     } 
     std::cout << ") = "<< sum << "\n "; 
     sum = 0; 
    } 

我重复印刷的最后一个元素,并在相同的测试 + 因为没有一双开始4,代码不会在这种情况下工作。

这个结果:

(1,2,3,4,4,4,4,4,4) = 3 
(1,2,3,4,4,4,4,4,4) = 3 
(1,2,3,4,4,4,4,4,4) = 3 
(2,1,1,1,3,4,5,5,5) = 7 
(2,1,1,1,3,4,5,5,5) = 7 
(2,1,1,1,3,4,5,5,5) = 7 
(3,5,1,1,2,2,2,4,4) = 5 
(5,4,4,4,4,4,2,2,4) = 2 

我刚学make_pair,花了阅读关于它4个小时,看看是否有任何例子或类似的问题,可以引导我,但没有运气!

回答

2

通过使用map(或如果您拥有C++ 11或来自boost的unordered_map),可以大大简化您的问题。

这个想法是在你的pair/frequency列表上迭代一次,并在地图上为每个key存储部分和。然后您可以在第二个循环中打印出总和。

#include <map> 

// ... 

std::map<int,int> sums; 
for (const auto& p1 : pairToCount) 
    sums[p1.first.first] += p1.second; 
    sums[p1.first.second] += p1.second; 
} 

for (const auto& k : sums) { 
    // print what you want 
} 
+0

谢谢,这段代码看起来很聪明,但我没有,我使用visual stdio 2013/vC++。因为这是我第一次听说boost和C++ 11,所以我阅读了一些相关的主题,(例如http://stackoverflow.com/questions/17440810/how-do-i-build-boost-with-new -visual-studio-2013-preview/17440811#17440811),对我来说听起来很复杂。 – NHA

+0

实际上,我只是改变了地图[p1.first.first] + = p1.second; map [p1.first.second] + = p1.second; **为**总和[p1.first.first] + = p1.second; sums [p1.first.second] + = p1.second;它的工作原理。谢谢你 – NHA

+0

啊,是的,错字。对于那个很抱歉。 – Mat