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

hw03 #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

hw03 #33

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: 25 additions & 3 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#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++) {
Expand All @@ -16,19 +17,40 @@ 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{});
std::vector<T0> ret;
for (size_t i = 0; i < std::min(a.size(), b.size()); i++) {
ret.push_back(a[i] + b[i]);
}
return ret;
}

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 const& a, auto const& b) {
return std::variant<T1, T2>{a + b};
}, a, b);
}

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

return os;
}

template<class T0 , class T1 , class T2>
auto operator+(std::variant<T0, T1> const& v, T2 const& x) {
return std::visit([&](auto const& a) {
return std::variant<T0, T1>{a + x};
}, v);
}

int main() {
Expand Down