0

有没有办法将一个内容连接TStringDynArray到另一个内容TStringDynArray

//First TStringDynArray
Item1
Item2
Item3

//Second TStringDynArray
ItemA
ItemB
ItemC

//Result after concatenate
Item1
Item2
Item3
ItemA
ItemB
ItemC
4

1 回答 1

1

不是直接的,因为System::DynamicArray在 C++ 中不提供串联功能。因此,您需要创建一个 3rd TStringDynArray,将其调整为 2 个数组大小的总和,然后将 2 个数组中的每个数组分别复制String到 3rd 数组中 (String是引用计数的,因此您不能只使用memcpy()or复制字节等价的,就像你可以使用普通类型的数组一样),例如:

TStringDynArray Arr1;
// fill Arr1 as needed...

TStringDynArray Arr2;
// fill Arr2 as needed...

TStringDynArray MergedArr;
MergedArr.Length = Arr1.Length + Arr2.Length;
int idx = 0;

for(int i = 0; i < Arr1.Length; ++i) {
    MergedArr[idx++] = Arr1[i];
}

for(int i = 0; i < Arr2.Length; ++i) {
    MergedArr[idx++] = Arr2[i];
}

// use MergedArr as needed...

或者(C++Builder 10.1 Berlin 及更高版本):

#include <algorithm>

TStringDynArray Arr1;
// fill Arr1 as needed...

TStringDynArray Arr2;
// fill Arr2 as needed...

TStringDynArray MergedArr;
MergedArr.Length = Arr1.Length + Arr2.Length;
std::copy(Arr1.begin(), Arr1.end(), MergedArr.begin());
std::copy(Arr2.begin(), Arr2.end(), MergedArr.begin() + Arr1.Length);

// use MergedArr as needed...

基于 Clang 的编译器中,您可以更进一步,通过使用一些可变参数模板函数来帮助您连接任意数量的输入TStringDynArray数组,例如:

#include <algorithm>

int ArrLength()
{
    return 0;
}

template<typename... Ts>
int ArrLength(TStringDynArray &arr, Ts&... others)
{
    return arr.Length + ArrLength(others...);
}

void ArrCopy(TStringDynArray::iterator dst)
{
}

template<typename... Ts>
void ArrCopy(TStringDynArray::iterator dst, TStringDynArray &arr, Ts&... others)
{
    std::copy(arr.begin(), arr.end(), dst);
    ArrCopy(dst + arr.Length, others...);
}

template<typename... Ts>
TStringDynArray ArrMerge(TStringDynArray &arr, Ts&... others)
{
    TStringDynArray res;
    res.Length = ArrLength(arr, others...);
    ArrCopy(res.begin(), arr, others...);
    return res;
}

...

TStringDynArray Arr1;
// fill Arr1 as needed...

TStringDynArray Arr2;
// fill Arr2 as needed...

TStringDynArray MergedArr = ArrMerge(Arr1, Arr2/*, Arr3, Arr4, ...*/);
// use MergedArr as needed...
于 2020-11-25T23:10:21.630 回答