打印出std :: vector <std :: wstring> </std :: wstring>

时间:2013-09-12 15:00:15

标签: c++ stl visual-studio-2005

我正在尝试调整this以使用std :: copy打印出std::vector<std::wstring>的内容,但我不明白该代码是如何运行良好的,并且无法将其转换为编译。代码应该是什么?

我使用了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的{​​{1}}时,它会告诉我wcout

1 个答案:

答案 0 :(得分: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"));
}
相关问题