提问者:小点点

STL算法函数在多个一维容器上的应用


我有一个简单结构

struct Point
{
    Point(int x, int y)
        : x(x)
        , y(y)
    {}
    
    int x, y;
};

和二维向量(也可以是三维向量或更多)

std::vector<std::vector<Point>> v(10, std::vector<Point>(10, Point(3, 4)));

我想知道所有x值的汇总。 我可以使用std::accumulation,它看起来像

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::accumulation的用法具有更好的可读性? 或者在这种情况下不适用。 当你有多个一维容器时,它是否普遍适用于使用STL?


共1个答案

匿名用户

如果您考虑STL的现状,那么嵌套的range-for循环可能是最易读的(尽管它仍然是主观的)。

但是,我非常主张不要使用range-for循环,除非您需要transformfor_eace。 如果代码正在执行累积,那么您应该编写一个累积

下面是我今天在range-v3的帮助下如何编写这段代码。 希望用不了多久,STL就能让你写出可读性很好的代码。

namespace rs = ranges;
namespace rv = ranges::views;

int sum = rs::accumulate(v | rv::join, 0, std::plus{}, &Point::x);

这是一个演示。