Skip to content
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

finish hw03 #45

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
28 changes: 24 additions & 4 deletions main.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#include <iostream>
#include <vector>
#include <variant>
#include "cpp_type_name.h"

// 请修复这个函数的定义:10 分
// 请修复这个函数的定义:10 分 (添加模板声明)
template<typename T>
std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
os << "{";
for (size_t i = 0; i < a.size(); i++) {
Expand All @@ -14,28 +16,46 @@ std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
return os;
}

// 请修复这个函数的定义:10 分
// 请修复这个函数的定义:10 分 (不应使用T0, 用auto代替)
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}
size_t len = std::min(a.size(), b.size());
std::vector<decltype(T1{} + T2{})> res(len);
for (size_t i = 0; i < len; ++i) {
res[i] += a[i] + b[i];
}
return res;
}

template<class T1, class T2>
std::variant<T1, T2> operator+(std::variant<T1, T2> const &a, T2 const &b) {
return a + std::variant<T1, T2>(b);
}

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

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

int main() {
std::vector<int> a = {1, 4, 2, 8, 5, 7};
std::cout << a << std::endl;
std::vector<double> b = {3.14, 2.718, 0.618};
std::cout << b << std::endl;

auto c = a + b;

// 应该输出 1
Expand All @@ -50,6 +70,6 @@ int main() {

// 应该输出 {9.28, 17.436, 7.236}
std::cout << d << std::endl;

return 0;
}