#include <iostream>
#include <numeric>
#include <vector>
using matrix = std::vector<std::vector<int>>;
int main()
{
matrix mtx{5, std::vector<int>(5)};
int sum = 0;
for (const auto i : mtx) // can be avoided ?
sum = std::accumulate(i.begin(), i.end(), 0,
[](int a, int b){a > 0 ? a b : a;});
}
我想使用std::accumulateforstd::vector<std::vector<int>>但我很好奇是否可以避免回圈。我也想知道最后一個論點是否可以。
uj5u.com熱心網友回復:
根據您的 lambda,您似乎只想對正條目求和:
#include <iostream>
#include <numeric>
#include <vector>
using Number = int;
using Matrix = std::vector<std::vector<Number>>;
int main() {
Matrix mtx{5, std::vector<Number>(5, 1)};
Number sum_positives = std::accumulate(
mtx.begin(), mtx.end(), Number(0), [](Number const acc, auto const &v) {
return std::accumulate(
v.begin(), v.end(), acc,
[](Number const a, Number const b) { return b > 0 ? a b : a; });
});
std::cout << sum_positives << std::endl; // 25
return 0;
}
不要忘記傳遞給的 lambdastd::accumulate()必須回傳一個值。
uj5u.com熱心網友回復:
C 20 范圍join_view對此特別有用,因為它們允許您將矩陣展平為向量。
所以你最終會得到一個像這樣的代碼:
int sum{0};
auto jv{ std::ranges::join_view(mtx) }; // flatten mtx into a list of ints
std::ranges::for_each(jv, [&sum](auto n) { sum = ((n > 0) ? n : 0); });
不幸的是,accumulate直到 C 23 ,ranges才可用:
auto sum{ std::ranges::accumulate(jv, 0, [](auto total, auto n) { return total ((n > 0) ? n : 0); }) };
對于用以下之間的亂數填充矩陣的完整樣本[-100, 100]:
[演示]
#include <algorithm> // for_each
#include <iostream> // cout
#include <random> // default_random_engine, uniform_int_distribution
#include <ranges> // for_each, join_view
#include <vector>
using matrix = std::vector<std::vector<int>>;
int main()
{
matrix mtx{3, std::vector<int>(3)};
// Fill matrix with random values between [-100, 100]
std::default_random_engine re{ std::random_device{}() };
std::uniform_int_distribution<int> dist{ -100, 100 };
std::for_each(std::begin(mtx), std::end(mtx),
[&dist, &re](auto& row) {
std::for_each(std::begin(row), std::end(row),
[&dist, &re](auto& n) { n = dist(re); }
);
}
);
auto jv{ std::ranges::join_view(mtx) }; // flatten mtx into a list of ints
// Print matrix
std::cout << "mtx = ";
std::ranges::for_each(jv, [](auto n) { std::cout << n << " "; });
std::cout << "\n";
// Sum all positive values in the matrix
int sum{0};
std::ranges::for_each(jv, [&sum](auto n) { sum = ((n > 0) ? n : 0); });
std::cout << "sum = " << sum << "\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/400662.html
