No matching constructor for initalization of 'ostream_iterator<int>'

南笙酒味 提交于 2019-12-18 06:24:07

问题


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;

回答1:


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)

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

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, ","));

If C++11 is available to you then

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

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".




回答2:


ostream_iterator constructor takes const CharT* delim as second parameter:

ostream_iterator(ostream_type& stream, const CharT* delim) (1)

ostream_iterator(ostream_type& stream) (2)

To make your code work, you need to pass in a string:

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



回答3:


The std::ostream_iterator takes a string as the second parameter to the constructor. This is the string that will be output after each integer in the sequence.



来源:https://stackoverflow.com/questions/17824266/no-matching-constructor-for-initalization-of-ostream-iteratorint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!