无法复制到输出迭代器

Cannot copy to the output iterator

本文关键字:输出 迭代器 复制      更新时间:2023-10-16

Helo。有人能告诉我为什么我可以分配给输出操作符,但不能对它执行复制吗?Copy需要OutputIterator作为三次参数,但我有一些奇怪的错误,你可以在这里看到:http://cpp.sh/5akdx

#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
bool space(const char &c) {
    return c == ' ';
}
bool not_space(const char &c) {
    return !space(c);
}
template<class Out>
void split(const string &str, Out os) {
    typedef string::const_iterator iter;
    iter i = str.begin();
    while (i != str.end()) {
        i = find_if(i, str.end(), not_space);
        iter j = find_if(i, str.end(), space);
        if (i != str.end())
            //*os++ = string(i, j); //THIS WORKS
            copy(i, j, os);  //THIS DOESN'T WORK
        i = j;
    }
}
int main()
{
    string s;
    while (getline(cin, s))
        split(s, ostream_iterator<string>(cout, "n"));
    return 0;
}

问题是这是

*os++ = string(i, j); 

但事实并非如此:

copy(i, j, os); 
*os++ = string(i, j); 

这一行从两个字符的迭代器中创建一个字符串,并将其写入输出迭代器。

copy(i, j, os); 

此行尝试将迭代器范围中的每个字符写入输出迭代器。

这意味着,当第一行将字符串写入输出迭代器时,第二行尝试写入单个字符。这两种类型不兼容,尤其是输出迭代器只接受字符串。这就是问题所在。