没有用于'ostream_iterator< int>'的初始化的匹配构造函数 [英] No matching constructor for initalization of 'ostream_iterator<int>'

查看:306
本文介绍了没有用于'ostream_iterator< int>'的初始化的匹配构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码,为什么错误,osteam_iterator是一个模板类,为什么没有匹配构造函数用于'ostream_iterator'的初始化,请给予帮助,谢谢。
define ostream_iterator
template>
class _LIBCPP_VISIBLE ostream_iterator

for the code, why error, osteam_iterator is a template class ,why no matching constructor for initalization of 'ostream_iterator', please give a help , thank you. define ostream_iterator template > class _LIBCPP_VISIBLE ostream_iterator

int main(int argc, const char * argv[])
{
    vector<int> sentence1;
    sentence1.reserve(5);// 设置每次分配内存的大小

    sentence1.push_back(1);
    sentence1.push_back(2);
    sentence1.push_back(3);
    sentence1.push_back(4);
    sentence1.push_back(5);

    int c = 5;

    copy(sentence1.begin(), sentence1.end(), ostream_iterator<int>(cout, 1));
    cout << endl;


推荐答案

ostream_iterator类定义如下:

The ostream_iterator class definition looks like:

template< class T,
  class CharT = char,
  class Traits = std::char_traits<charT>>
class ostream_iterator /*...*/

而相应的构造函数声明为:

whereas the respective constructor is declared as:

ostream_iterator(ostream_type& buffer, const CharT* delim)

由于 ostream_iterator 的第二个模板参数必须是字符类型,因此不能简单地用int替换它。

Since the second template argument of an ostream_iterator is required to be of character type you cannot simply replace it with int.

如果省略第二个模板参数,可以插入类型为 char const * 的字符串文字:

If you ommit the second template parameter you can plug in a string literal of type char const *:

std::copy(sentence1.begin(), sentence1.end(), std::ostream_iterator<int>(cout, ","));

如果您可以使用C ++ 11,那么

If C++11 is available to you then

int c = 5;
for ( auto v : sentence1 ) std::cout << v << c;

是做你应得的另一种方式,也可能是合适的。
优点是,运算符<< 比指向char类型的指针类型的参数更灵活。

is another way of doing what you deserve and it might be suitable, too. The advantage is, that operator<< is more flexible than an argument of type "pointer to char type".

这篇关于没有用于'ostream_iterator&lt; int&gt;'的初始化的匹配构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆