'ostream_iterator<int>'的初始化没有匹配的构造函数
代码,为什么出错,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".
相关文章