gpt4 book ai didi

c++ - 使用 STL/Boost 查找和修改 vector 中的匹配元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:49:28 25 4
gpt4 key购买 nike

假设我有一个这样声明的 vector :

struct MYSTRUCT
{
float a;
float b;
};

std::vector<MYSTRUCT> v;

现在,我想找到 v 中共享相同 a 的所有元素,然后对它们的 b 进行平均,即

假设 v 包含这五个元素 {a, b}:{1, 1}, {1, 2}, {2, 1}, {1, 3}, {2, 2}

我想得到 v[0]、v[1]、v[3](其中 a 为 1)和平均值 b:(1 + 2 + 3)/3 = 2,以及 v[2] 和 v [4](其中 a 为 2)和平均 b:(1+2)/2 = 1.5

之后 v 将如下所示:{1, 2}, {1, 2}, {2, 1.5}, {1, 2}, {2, 1.5}

我不太熟悉 STL 或 Boost,所以我只能弄清楚如何在 C++ 中以“暴力”方式执行此操作,但我猜测 STL(for_each?)和 Boost(lambda?)库可以更优雅地解决这个问题。

编辑 仅供引用,这是我的(有效)蛮力方法:

for(int j = 0; j < tempV.size(); j++)
{
MYSTRUCT v = tempV.at(j);
int matchesFound = 0;

for(int k = 0; k < tempV.size(); k++)
{
if(k != j && v.a == tempV.at(k).a)
{
v.b += tempV.at(k).b;
matchesFound++;
}
}

if(matchesFound > 0)
{
v.b = v.b/matchesFound;
}

finalV.push_back(v);
}

最佳答案

只是大声思考,这可能会变得相当愚蠢:

struct Average {
Average() : total(0), count(0) {}
operator float() const { return total / count; }
Average &operator+=(float f) {
total += f;
++count;
}
float total;
int count;
};

struct Counter {
Counter (std::map<int, Average> &m) : averages(&m) {}
Counter operator+(const MYSTRUCT &s) {
(*averages)[s.a] += s.b;
return *this;
}
std::map<int, Average> *averages;
};

std::map<int, Average> averages;
std::accumulate(v.begin(), v.end(), Counter(averages));
BOOST_FOREACH(MYSTRUCT &s, v) {
s.b = averages[s.a];
}

嗯。不完全愚蠢,但也许也不引人注目......

关于c++ - 使用 STL/Boost 查找和修改 vector 中的匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406995/

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