所以今天在测试中,我们有一段代码,我们有代码的输出,我们需要编写该函数。
std::vector<double> v;
auto z = first(v);
std::cout << z << std::endl; // OUTPUT: No value!
v.push_back(3.14);
z = first(v);
std::cout << z << std::endl; // OUTPUT: 3.14
我们需要编写的函数是first()
。它接受任何类型的 vector 作为参数,并返回 vector 的第一个元素(如果 vector 不为空)。
我是这样做的:
template <typename T>
std::string first(const std::vector<T>& ve){
if(ve.empty())
return "No value!";
else
return std::to_string(*(ve.begin()));
}
当我问老师to_string()
是怎么回事时,因为我不知道to_string()
的名字是什么,他说我不知道需要它,因为 auto z = first(v)
不应该是字符串。
如果 first()
不返回字符串,我该如何获取输出 No value!
?
最佳答案
有first()
返回 std::optional<T>
,其中如果 ve
为空则返回std::nullopt
,否则返回v.front()
.
然后过载operator<<
打印std::optional<T>
.
例如:
#include <optional>
template <typename T>
std::optional<T> first(const std::vector<T>& ve){
if (ve.empty())
return std::nullopt;
else
return ve.front();
}
template <typename T>
std::ostream& operator<<(std::ostream& os, std::optional<T>& op) {
if (op.has_value())
os << op.value();
else
os << "No value!";
return os;
}
关于c++ - 一个函数可以有两种不同的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68943445/