How to convert List of arrays to two dimensional array?

visual-c++ collections c++-cli

83 просмотра

1 ответ

I have a list of arrays where I added many arrays but all of them are the same size. Now I want convert this list to two dimensional array. I tried in this way:

List<Array^>^ vList = gcnew List<Array^>();
//some code where I add elements to vList
array<String ^, 2> ^ anArray = gcnew array<String ^, 2>(vList->Count, 5);
anArray = vList->ToArray();

But I have got this error:

a value of type "cli::array<System::Array ^, 1> ^" cannot be assigned to an entity of type "cli::array<System::String ^, 2> ^"

I don't know how to convert it.

Автор: Piotr Wasilewicz Источник Размещён: 08.11.2019 11:17

Ответы (1)


1 плюс

Решение

You're going to have to iterate and copy all of the strings individually. However, the raw type Array^ isn't that convenient to work with, so you'll need to do something about that.

Basically, what you need to do is this:

for (int outer = 0; outer < vList->Count; outer++)
{
    arrayOfSomeSort^ innerArray = vList[outer];
    for (int inner = 0; inner < innerArray.Length; inner++)
        anArray[outer, inner] = innerArray[inner];
}

Depending on how the rest of the program is, and what objects are actually in the List, there are a few options on what to do. Here are the options I see, in order of preference.

  1. Instead of a List<Array^>^, have vList be a List<array<String^>^>^. If the List truly is a list of string arrays, then this option is probably the most correct. In this case, arrayOfSomeSort^ would be array<String^>^.
  2. If vList can't change type, but it does indeed contain string arrays, then I'd have the local variable innerArray be of type array<String^>^, and do a cast as you pull it out of vList.
  3. If the arrays in the list aren't string arrays, but instead are object arrays that happen to contain strings, then I'd have array<Object^>^ innerArray, and cast to that instead, and do a cast to String^ as you pull each string out of innerArray.
  4. If none of those is appropriate, then you can leave innerArray as type Array^. You'll need to call the explicit method Array.GetValue(int) instead of using the [] indexer. As with the previous option, you'll need to cast each string as you pull it out of the inner array.

You've set the second dimension to 5 without checking the lengths of the inner arrays; I'm assuming you know something we don't, and are sure that there won't be anything larger than 5. If not, you'll need to iterate the list once to get the maximum array size, create the 2D array, and then copy the strings.

Автор: David Yaw Размещён: 20.08.2016 04:09
Вопросы из категории :
32x32