gpt4 book ai didi

c++ - 使用 make_pair 后对一些对进行分组

转载 作者:行者123 更新时间:2023-11-28 02:59:28 32 4
gpt4 key购买 nike

使用make_pair后,我得到了一些pairToCount

在这种格式中(元素 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 个小时阅读它,看看是否有任何示例或类似问题可以指导我,但没有运气!

最佳答案

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

想法是在您的配对/频率列表上迭代一次,并将每个键的部分总和存储在映射中。然后,您可以在第二个循环中打印出总和。

#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
}

关于c++ - 使用 make_pair 后对一些对进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21214404/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com