[英]C++ basic custom cout printing to consle
template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{
os << s << " = (\n";
os << charInput1;
std::copy(first, last, std::ostream_iterator<int>(std::cout, "\n"));
os << charInput2;
os << "\n)";
}
我正在尝试进行自定义提示打印。 该成员函数属于CustomPrinter
类,并且charInput1
和charInput2
是其私有char
成员,在构造自定义打印机时会定义它们。 第first
和last
应该是迭代器,并且s
是一个字符串。
因此,例如,给定的charInput1
是一个+
号,而charInput2
是一个句点.
,在std::vector<int> = {1, 1, 1}
的情况下,我希望最终输出如下:
(
+1.
+1.
+1.
)
但是我越来越
(
+1
1
1
.
)
所以我的问题是,要在每个矢量元素之间打印给定的char
,还需要什么? 是否可以仅使用std::ostream_iterator<int>(std::cout, /* char here? */)
? 因为似乎此方法只能在之间插入字符串,所以我也需要在前面插入。 如果没有,有什么更好的方法? 提前致谢!
编辑:在我主要
CustomPrinter cp(std::cout, '+', '.');
std::vector<int> v = {1, 1, 1};
cp.print("result", v.begin(), v.end()); // function call..
只需使用普通循环即可:
template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{
os << s << " = (\n";
for (auto el = first; el != last; el++) {
os << charInput1 << *el << charInput2 << "\n";
}
os << ")";
}
实际上,您可以使用std::ostream_iterator
,方法是串联周围的字符。
template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{
std::string sep = charInput1 + std::string("\n") + charInput2;
os << s << " = (\n";
if (first != last) { // Don't print first prefix and last suffix if the sequence is empty
os << charInput1;
std::copy(first, last, std::ostream_iterator<int>(std::cout, sep.c_str()));
os << charInput2;
}
os << "\n)";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.