英文:
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 <numeric>
#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int>> 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& size, const auto& vec)
{
return size + vec.size();
});
std::cout << accumulated_sum << "\n";
// simple range based for loop
std::size_t sum{0ul};
for (const auto& values : list_of_values) sum += values.size();
std::cout << sum << "\n";
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论