1

我试图调整以打印出std::vector<std::wstring>使用 std::copy 的内容,但我不明白该代码如何运行得足够好,并且无法编译。代码应该是什么?

我使用了 Rob 的示例,但它不起作用:

std::vector<std::wstring> keys = ...;
std::copy(keys.begin(), keys.end(), std::ostream_iterator<std::wstring>(std::wcout, " "));

我得到错误:

1>error C2665: 'std::ostream_iterator<_Ty>::ostream_iterator' : none of the 2 overloads could convert all the argument types
1>        with
1>        [
1>            _Ty=std::wstring
1>        ]
1>        C:\Program Files\Microsoft Visual Studio 8\VC\include\iterator(300): could be 'std::ostream_iterator<_Ty>::ostream_iterator(std::basic_ostream<_Elem,_Traits> &,const _Elem *)'
1>        with
1>        [
1>            _Ty=std::wstring,
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        while trying to match the argument list '(std::wostream, const char [2])'

为什么_Elem=char当我使用wcoutwhich is of type时它会告诉我wostream

4

1 回答 1

5

您必须wstring, wchar_t用作模板参数,并wcout用作输出流:

std::copy(v.begin(), 
          v.end(), 
          std::ostream_iterator<std::wstring, wchar_t>(std::wcout, L"\n"));

测试程序:

#include <vector>
#include <string>
#include <iostream>
#include <iterator>

int main () {
  std::vector<std::wstring> v;
  v.push_back(L"Hello");
  v.push_back(L"World");
  std::copy(v.begin(),
            v.end(),
            std::ostream_iterator<std::wstring, wchar_t>(std::wcout, L"\n"));
}
于 2013-09-12T15:04:58.377 回答