質問

I was trying to adapt this to print out the contents of std::vector<std::wstring> using std::copy but I don't understand how that code is working well enough, and can't get it to compile. What should the code be?

I used Rob's example but it doesn't work:

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

I get the error:

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])'

Why is it telling me _Elem=char when I use wcout which is of type wostream?

役に立ちましたか?

解決

You must use wstring, wchar_t as the template parameters, and wcout as the output stream:

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

Test program:

#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"));
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top