gpt4 book ai didi

c++ - C++ 中两个 map 之间的同时并集和交集

转载 作者:行者123 更新时间:2023-12-01 18:57:06 27 4
gpt4 key购买 nike

在做一个大学项目时,我遇到了以下问题:我有两个映射(Kmer1 和 Kmer2),它们由字符串(键)和整数(值)组成。我必须计算遵循此公式的距离

[1-(I/U)]*100

Where...
...U = the sum of all int values inside Kmer1 U Kmer2
...I = the sum of all int values inside Kmer1 ∩ Kmer2

Consider that...
... The U and ∩ are made evaluating the keys (strings)
... When an element is in both maps:
- At the Union we add the one with higher int value
- At the Intersection we add the one with lower int value

示例:

Kmer1 = AAB¹ AAC¹ AAG³
Kmer2 = AAG¹ AAT² ABB¹

Union = AAB¹ AAC¹ AAG³ AAT² ABB¹ U= 8
Intersection = AAG¹ I= 1
Distance = 87.5

编码时间!我一直在尝试解决它,但所有解决方案都像......部分正确,并非所有情况都涵盖在内。因此,当我试图覆盖它们时,我以无限循环、异常上升、if-else 的长长嵌套(这太糟糕了..)结束,无论如何,这是最不糟糕且不起作用的尝试:

设置:

Species::Kmer Kmer1, Kmer2;        //The two following lines get the Kmer from another
Kmer1 = esp1->second.query_kmer(); //object.
Kmer2 = esp2->second.query_kmer();

Species::Kmer::const_iterator it1, it2, last1, last2;
it1 = Kmer1.cbegin(); //Both Kmer are maps, therefore they are ordered and
it2 = Kmer2.cbegin(); //whitout duplicates.
last1 = --Kmer1.cend();
last2 = --Kmer2.cend();

double U, I;
U = I = 0;

应用公式的循环:

while (it1 != Kmer1.cend() and it2 != Kmer2.cend()){
if (it1->first == it2->first) {
if (it1->second > it2->second) {
U += it1->second;
I += it2->second;
} else {
U += it2->second;
I += it1->second;
}
++it1;
++it2;

} else if (it1->first < it2->first) {
U += it1->second;
++it1;
} else {
U += it2->second;
++it2;
}
}

请注意,我没有先创建并集和交集,然后计算每个值的总和,而是直接跳转到值的总和。我知道也许这并不难,但我一直在努力解决它,但我几乎陷入困境......

<小时/>
I've uploaded the whole code at Github: (Maybe it helps)
- There is a makefile to build the code
- There is a file called input.txt with a sample for this specific problem
- Also inside the input.txt, after line13 (fin) I've added the expected output
- Executing ./program.exe < input.txt should be enough to test it.

https://github.com/PauGalopa/Cpp-Micro-Projects/tree/master/Release

<小时/>

重要是的!我知道几乎所有的 STL 功能都可以在几行内完成此操作,但是......由于这是一个大学项目,我必须受到教学大纲的限制,因此请考虑我只允许使用“ map ”“字符串”“vector ”等。不,我不能使用“算法”(我真的希望我可以)我将在评论中澄清对我可以做或使用哪些事情的任何疑问。

最佳答案

在主 while 循环之后添加这两个循环。

while (it1 != Kmer1.cend()){
U += it1->second;
it1++;
}
while (it2 != Kmer2.cend()){
U += it2->second;
it2++;
}

关于c++ - C++ 中两个 map 之间的同时并集和交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61634593/

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