diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 6b39b6d..71fe3e9 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -29,4 +29,4 @@ add_example(multinary_ex OFF) add_example(text_io_ex OFF) add_example(getoption_ex OFF) add_example(process_ex OFF) -add_example(array_ex OFF) \ No newline at end of file +add_example(array_ex ON) \ No newline at end of file diff --git a/example/array_ex.cpp b/example/array_ex.cpp index 08f39d9..9f4ab9f 100644 --- a/example/array_ex.cpp +++ b/example/array_ex.cpp @@ -42,7 +42,7 @@ int main(int argc, char const *argv[]) try A.linear2log(2); A.show(); - A.parallel_for_each([](double &a, size_t i){a += 1;}); + A.for_each([](double &a){a += 1;}); A.show(); A.sequence(1.0, 0.5, 3, 4, 1); @@ -64,6 +64,9 @@ int main(int argc, char const *argv[]) try P.sequence(point3dc(0, 0, 0), point3dc(2, 1, 0.5)); P.show(std::cout, '\n'); + array Px = P.extract([](const point3dc &p)->double{return p.x;}); + Px.show(); + // create a new 2D array matrix C(5, 5, 1); C.sequence(0, 1, 10); diff --git a/lib/core/array.h b/lib/core/array.h index 9d89361..3b63eb0 100644 --- a/lib/core/array.h +++ b/lib/core/array.h @@ -593,22 +593,45 @@ namespace gctl /** * @brief 并行执行指定操作 * - * 对数组中的每个元素并行执行给定的操作,第一个参数为数组元素的引用,第二个参数为元素的索引。 - * 例如:[](ArrValType &a, size_t i){do something here...} + * 对数组中的每个元素并行执行指定的操作,参数为数组元素的引用。 + * 例如:[](ArrValType &a){do something here...} * - * @tparam BiaryOp 二元操作类型 第一个参数为数组元素的引用,第二个参数为元素的索引 + * @tparam UnaryOp 一元操作类型 参数为数组元素的引用 * @param op 要执行的操作 */ - template - void parallel_for_each(BiaryOp op) + template + void for_each(UnaryOp op) { #pragma omp parallel for for (size_t i = 0; i < length_; i++) { - op(val_[i], i); + op(val_[i]); } + return; } + /** + * @brief 并行执行提取操作(比如提取结构体的成员变量数组) + * + * 对数组中的每个元素并行执行给定的操作并将输出组成一个新数组,参数为数组元素的常引用。 + * 例如:[](const ArrValType &a)->OutType{do something here...} + * + * @tparam UnaryOp 一元操作类型 参数为数组元素的引用 + * @param op 要执行的操作 + */ + template + array extract(UnaryOp op) + { + array arr(length_); + #pragma omp parallel for + for (size_t i = 0; i < length_; i++) + { + arr[i] = op(val_[i]); + } + return arr; + } + + /** * @brief Display the elements. *