Skip to content

hw03-frsama #43

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
#include <variant>

// 请修复这个函数的定义:10 分
template <class T>
std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
os << "{";
for (size_t i = 0; i < a.size(); i++) {
for (size_t i = 0; i < a.size(); ++i) {
os << a[i];
if (i != a.size() - 1)
os << ", ";
Expand All @@ -16,19 +17,52 @@ std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {

// 请修复这个函数的定义:10 分
template <class T1, class T2>
std::vector<T0> operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
auto operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
// 请实现列表的逐元素加法!10 分
// 例如 {1, 2} + {3, 4} = {4, 6}
using T0 = decltype(T1{} + T2{});
int n = (a.size() < b.size() ? a.size() : b.size());
std::vector<T0> res;
for(int i = 0; i < n; ++i){
res.push_back(a[i] + b[i]);
}
return res;
}

//缺少vector<double>与variant<vector<int>, vector<double>>相加的重载,故增加
template <class T1, class T2, class T3>
auto operator+(std::variant<T1, T2> const &a, std::vector<T3> const &b) {
return std::visit(
[&](auto const &a) -> std::variant<T1, T2> {
return a + b;
}, a);
}

template <class T1, class T2, class T3>
auto operator+(std::vector<T1> const &a, std::variant<T2, T3> const &b) {
return std::visit(
[&](auto const &b) -> std::variant<T1, T2> {
return a + b;
}, b);
}

template <class T1, class T2>
std::variant<T1, T2> operator+(std::variant<T1, T2> const &a, std::variant<T1, T2> const &b) {
auto operator+(std::variant<T1, T2> const &a, std::variant<T1, T2> const &b) {
// 请实现自动匹配容器中具体类型的加法!10 分
return std::visit(
[](auto const &a, auto const &b) -> std::variant<T1, T2> {
return a + b;
}, a, b);
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &os, std::variant<T1, T2> const &a) {
// 请实现自动匹配容器中具体类型的打印!10 分
std::visit(
[&](auto const &a){
os << a;//获取到特定type后直接调用vector的输出方式
}, a);
return os;
}

int main() {
Expand Down