我有一个简单的结构
struct Point
{
Point(int x, int y)
: x(x)
, y(y)
{}
int x, y;
};
和一个二维 vector (也可以是一个三维 vector 或更多)std::vector<std::vector<Point>> v(10, std::vector<Point>(10, Point(3, 4)));
我想知道所有 x 值的摘要。我可以使用 std::accumulate ,它看起来像
int sum = std::accumulate(v.begin(), v.end(), 0, [](int init, const auto& vec)
{
return init + std::accumulate(vec.begin(), vec.end(), 0, [](int init, Point p)
{
return init + p.x;
});
});
或者我可以为for (const auto& vec : v)
{
for (const auto& p : vec)
{
sum += p.x;
}
}
它看起来更具可读性(imo)。我应该改变什么才能使 std::accumulate 的使用具有更好的可读性?或者在这种情况下不适用。当您有多个一维容器时,是否通常适用于使用 STL?
最佳答案
如果您考虑现在的 STL,那么嵌套的 range-for 循环可能是最易读的(尽管它仍然是主观的)。
但是,我非常提倡不要使用 range-for 循环,除非您需要 transform
或 for_each
.如果代码正在执行 accumulate
,那么你应该写一个 accumulate
.
这是我今天在 range-v3 的帮助下编写此代码的方式。不久之后,STL 将让您编写具有可读性的代码。
namespace rs = ranges;
namespace rv = ranges::views;
int sum = rs::accumulate(v | rv::join, 0, std::plus{}, &Point::x);
这是一个 demo .
关于c++ - 在一维容器上使用 STL 算法函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62757360/