No matching constructor for initalization of #39;ostream_iteratorlt;intgt;#39;(ostream_iteratorlt;intgt;的初始化没有匹配的构造函数)
问题描述
代码,为什么出错,osteam_iterator是一个模板类,为什么'ostream_iterator'的初始化没有匹配的构造函数,请帮忙,谢谢.定义 ostream_iterator模板 >类_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;
是另一种做你应得的事情的方式,它也可能是合适的.优点是 operator<<
比指向 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<int>'的初始化没有匹配的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'ostream_iterator<int>'的初始化没有匹配的构造函数


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01