c++ - 在一维容器上使用 STL 算法函数

标签 c++ stl

我有一个简单的结构

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 循环,除非您需要 transformfor_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/

相关文章:

c++ - 将空范围(相同的迭代器)传递给 STL 算法是否会导致定义的行为?

qt - 将 std::ostream 转换为某个数组?

c++ - 将 vector 作为参数传递并使用它,为什么会崩溃?

c++ - Union hack 用于字节序测试和字节交换

c++理解在清理后访问全局变量不会给出某种错误

c++ - DirectX::XMVECTOR 函数 XMVectorSetByIndex() 未设置 float (C++)

V8 中的 Javascript 等价物?

c++ - 在 boost python 中使用自定义智能指针

c++ - 基于范围的 for 循环可以知道结尾吗?

c++ - 用于通信的二进制缓冲区,C++