2016-04-14 97 views
0

Helo。有誰能告訴我爲什麼我可以分配給輸出操作員,但不能在其上執行拷貝?複製需要輸出迭代器作爲THRID的說法,但我已經得到了一些奇怪的錯誤,你可以在這裏看到: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); 

但事實並非如此:

​​
+1

不工作需要'std :: ostream_iterator ',注意'char',而不是'string'。 'i'和'j'在字符串中迭代'char'。 – WhozCraig

回答

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

該行從兩個字符迭代器中創建一個字符串並將其寫入t輸出迭代器。

​​

此行嘗試將迭代器範圍中的每個字符寫入輸出迭代器。

這意味着雖然第一行將字符串寫入輸出迭代器,但第二行嘗試寫入單個字符。這兩種類型不兼容,特別是輸出迭代器只接受字符串。那就是問題所在。