-
Notifications
You must be signed in to change notification settings - Fork 139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
集思广益一下第15题 #159
Comments
coroutine有出过吗 |
没有,对,有道理,出点协程和模块吧 |
@rsp4jack 你去出一个协程的题目,出了我看看,讨论讨论 |
@Mq-b 我是卢瑟,不会 C++ 协程 |
不会?那快去学,卢瑟 |
感觉不如搞个 表达式模板(Expression Template) 的题,正好 mqb 在搞模板教程,还能学习 ranges 库 |
表达式模板是啥玩意? |
你好,这是Bing。表达式模板是一种C++编程技术,它通过模板元编程的方式,将复杂的计算表达式在编译期间展开,从而实现对计算过程的优化。 表达式模板的核心思想是利用模板的递归实例化来构建一个编译期的表达式树,然后在最后赋值时,一次性计算出表达式的结果,避免了中间变量的产生和多次循环的开销。 表达式模板的一个典型应用是优化科学计算中的向量和矩阵运算,例如Blitz++库就是基于表达式模板的高性能数值计算库。 |
什么卢瑟,你要出可以直接写,提讨论或者pr,到时候再附带解释。 |
题目要求:
#include <print>
#include <vector>
#include <algorithm>
#include <functional>
#include <ranges>
// 为std::vector增加一个自定义的赋值函数
template<typename T>
requires std::disjunction_v<std::is_integral<T>, std::is_floating_point<T>>
class vector : public std::vector<T> {
public:
using std::vector<T>::vector;
using std::vector<T>::size;
using std::vector<T>::operator[];
template<typename E>
vector<T>& operator=(const E& e) {
const auto count = std::min(size(), e.size());
this->resize(count);
for (std::size_t idx{ 0 }; idx < count; ++idx) {
this->operator[](idx) = e[idx];
}
return *this;
}
};
/*
// 实现表达式模板类及相关函数
template<...>
struct vector_expr {
};
// operator+
// operator-
// operator*
// operator/
*/
int main() {
auto print = [](const auto& v) {
std::for_each(std::begin(v), std::end(v), [](const auto& e) {
std::print("{}, ", e);
});
std::println("");
};
const vector<double> a{ 1.2764, 1.3536, 1.2806, 1.9124, 1.8871, 1.7455 };
const vector<double> b{ 2.1258, 2.9679, 2.7635, 2.3796, 2.4820, 2.4195 };
const vector<double> c{ 3.9064, 3.7327, 3.4760, 3.5705, 3.8394, 3.8993 };
const vector<double> d{ 4.7337, 4.5371, 4.5517, 4.2110, 4.6760, 4.3139 };
const vector<double> e{ 5.2126, 5.1452, 5.8678, 5.1879, 5.8816, 5.6282 };
{
vector<double> result(6);
for (std::size_t idx = 0; idx < 6; idx++) {
result[idx] = a[idx] - b[idx] * c[idx] / d[idx] + e[idx];
}
print(result);
}
{
vector<double> result(6);
result = a - b * c / d + e; // 使用表达式模板计算
print(result);
}
return 0;
} 学习链接:
|
No description provided.
The text was updated successfully, but these errors were encountered: