Question

I need to use in C++ programm vectors containing c-string of wchar_t. I tried to make it so:

using std::vector;

vector<wchar_t[SIZE]> string_list(100);

But I get large error output containing the following words:

error: functional cast to array type «std::vector<wchar_t [512]>::value_type {aka wchar_t [512]}»

What do I do incorrectly? Why I get such error?

Was it helpful?

Solution

Unfortunately raw arrays do not match* std::vector's requirements for an element type due to the many oddities of array types.

If you really want fixed-size arrays you should use std::array<wchar_t,SIZE>, as the std::array template fixes the problems with raw arrays and instead produces objects that act like proper values (e.g., a std::array<wchar_t,SIZE> is assignable whereas raw arrays are not).

However if you want string data and the strings aren't all going to be the same fixed size then you should not use arrays at all. You should most likely use std::wstring:

std::vector<std::wstring> string_list;


* Unless I'm mistaken, it actually is legal according to the C++11 spec to say std::vector<wchar_t[100]> v(100); because doing this alone doesn't place any requirements on the element type except that it be default constructible, which arrays are. However doing most anything useful with v does require more from the element type than arrays provide.

OTHER TIPS

You cannot declare vectors of arrays in C++. One approach is to put your array inside a struct and then use that struct inside your vector.

struct WCharArray
{
  wchar_t a[SIZE];
};

vector<WCharArray> string_list(100);

You cannot make a vector of an array because arrays are, well, weird.

You have several options instead:

  1. If your strings are static you can use a vector of pointers vector<wchar_t*>.
  2. If you really need a vector of arrays, wrap the array into a struct:
  3. If available, you can use the array template: vector< array<wchar_t, SIZE> >.

Option 2 will look like:

struct WArray
{
    wchar_t s[SIZE];
};
vector<WArray> string_list;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top