如何使用std::accumulate获取所有子向量的大小?

huangapple go评论76阅读模式
英文:

How to get a size of all subvectors using std::acumulate?

问题

我保存了一个类型为QVector<QVector<MyKlass>>的变量,如何使用std::accumulate来获取子向量大小之和?

使用基本算法,我可以这样做:

for(QVector<MyKlass> &data: datas)
{
    m_countOfSamples += data.size();
}

但如何使用STL来实现呢?

英文:

I save a variable of type QVector<QVector<MyKlass>>, how I can get a number that would be a sum of subvector size using std::accumulate?

Using basic alorithms i can make the same:

for(QVector<MyKlass> &data: datas)
{
    m_countOfSamples+=data.size();
}

But how make it using stl?

答案1

得分: 1

I think accumulate is not the best fit, but here is an example :

#include <numeric>
#include <vector>
#include <iostream>

int main()
{
    std::vector<std::vector<int>> list_of_values
    {
        { 1, 2, 3},
        { 4,5 },
        { 6, 7, 8, 9 }
    };

    // 使用 accumulate
    auto accumulated_sum = std::accumulate(list_of_values.begin(), list_of_values.end(), std::size_t{0ul},
        [](const auto& size, const auto& vec)
        {
            return size + vec.size();
        });

    std::cout << accumulated_sum << "\n";

    // 简单的基于范围的循环
    std::size_t sum{0ul};
    for (const auto& values : list_of_values) sum += values.size();
    std::cout << sum << "\n";

    return 0;
}

(Note: This code is provided in Chinese, as requested, but it's the same code you provided with translated comments.)

英文:

I think accumulate is not the best fit, but here is an example :

#include &lt;numeric&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;

int main()
{
    std::vector&lt;std::vector&lt;int&gt;&gt; list_of_values
    {
        { 1, 2, 3},
        { 4,5 },
        { 6, 7, 8, 9 }
    };

    // with accumulate
    auto accumulated_sum = std::accumulate(list_of_values.begin(), list_of_values.end(), std::size_t{0ul},
        [](const auto&amp; size, const auto&amp; vec)
        {
            return size + vec.size();
        });

    std::cout &lt;&lt; accumulated_sum &lt;&lt; &quot;\n&quot;;

    // simple range based for loop
    std::size_t sum{0ul};
    for (const auto&amp; values : list_of_values) sum += values.size();
    std::cout &lt;&lt; sum &lt;&lt; &quot;\n&quot;;

    return 0;

}

huangapple
  • 本文由 发表于 2023年6月29日 17:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定