根据一列中的相同值合并二维向量中的行
我有一个 2d 向量,有 6 列和 500 行。我想通过比较单个列值(PDG_ID)来组合行,即如果行的 PDG_ID 列值相同,我将取其他五列的平均值并存储这些行作为一行。 知道如何在 C++ 中做到这一点吗? 六列二维向量
I have a 2d vector which has 6 columns and 500 rows.I want to combine the rows by comparing a single column value(PDG_ID)i.e. if the PDG_ID colum value is same for rows,i will take the mean of other five columns and store these rows as one row.
Any idea how to do that in c++?
2d vectror with six columns
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要了解要求,然后选择合适的设计。
在您的情况下,您希望对具有相同 ID 的多行进行分组,并计算数据条目的平均值。
因此,1个ID和1个或多个数据条目之间存在关系。或者在 C++ 中,一个 ID 与一个或多个条目相关联。
在 C++ 中,我们有所谓的关联容器,例如
std::map
或std::unordered_map
。在这里,我们可以存储一个密钥(ID)和许多关联数据。如果我们将一行的所有数据放入结构体中,我们可以这样写:
并且,如果我们想要存储与多个 PDG 相关的 ID,我们可以定义一个这样的映射:
在这个映射中,我们可以存储 ID 和相关数据由一个或多个 PDG 组成。
然后我们可以添加一些非常小/简单的辅助函数,例如 IO 功能或平均值的计算。这样,我们就能将大的、更复杂的问题分解成更简单的部分。
然后,整体实现可能如下所示:
使用如下输入文件:
我们得到以下输出:
You need to understand the requirements and then select a fitting design.
In your case, you want to group several rows, having the same ID, and calculate the mean values of the data entries.
So, there is a relation between 1 ID and 1 or many data entries. Or in C++, an ID has associated one or many entries.
In C++, we have so called associative containers, like
std::map
orstd::unordered_map
. Here, we can store a key (the ID) with many associated data.If we put all data of one row into on struct, we could write something like:
And, if we want to store IDs with associated many PDGs, we can define a map like this:
In this map, we can store IDs and associated data consisting of one or many PDGs.
Then we can add some very small/simple helper functions, like for example for IO functionality or calculation of a the mean values. With that we break down big, more complicated problems into simpler parts.
Then, the overall implementation could loook like the below:
With an input file like:
we get the below output: