2016-12-13 106 views
0
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)"; 
} 

我想要做一个自定义的cout打印。此成员函数属于类别CustomPrinter,并且charInput1charInput2是其私有的char成员,它是在构建自定义打印机时定义的。 firstlast应该是迭代器,而s是一个字符串。C++基本定制cout打印到consle

因此,例如,给予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.. 
+0

后你是如何调用该函数一个完整的,可编译例子。 –

+0

@latedeveloper嗨,我已经添加了如何调用该函数。 – user3941584

+0

为什么你硬编码''作为'ostream_iterator'的类型名?它不应该来自类模板吗? – Barmar

回答

0

只需使用普通的循环:

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)"; 
} 
+0

谢谢!您的编辑功能非常有用,并且是我寻找的内容,除了您在循环中的建议外,当然也适用。 – user3941584

+0

顺便说一句,你的编译器抱怨'ostream_iterator(std :: ostream&,std :: string&)'? – user3941584

+0

我没有尝试过,但我现在看到'delimiter'必须是'char *',而不是'std :: string'。我用'.c_str()'来获取它。 – Barmar