我正在编写一个 C++ dll 来对从 VBA 传递的 SAFEARRAY 进行排序。
我没有使用任何 OLE 库,而是直接访问数组描述符和数据。
我对任何本机 VBA 类型的数组进行排序都没有问题。例如,以下片段对 BSTR 数组进行排序:
long * p = (long*)pData;
std::sort(p, p + elems, comparestring);
...使用此比较功能:
bool comparestring(const long& lhs, const long& rhs) {
wchar_t * lhs_ = (wchar_t*)lhs;
wchar_t * rhs_ = (wchar_t*)rhs;
return _wcsicmp(lhs_, rhs_) < 0;
}
我意识到我在这里作弊,因为wchar_t
它与 非常不同BSTR
,但是在 Excel 字符串的有效负载中包含零字符并不常见,所以我可以接受。以上效果很好。
问题
我希望 dll 能够选择性地将索引的伴随数组排序到主数据数组中。在这种模式下,只有索引数组会被排序,而源数据保持不变。
我的研究表明 lamda 函子可能是最有希望的路径,因为我不希望为额外的数组或数据或对的向量分配内存。
特别是,这个答案似乎很有希望。
但是,我无法弄清楚如何使其适应我正在处理从 pData 开始的 BSTR 的原始指针的情况。
我尝试了以下方法:
long * p = (long*)pData;
long ndx[5];
for (int i = 0; i < 5; i++) ndx[i] = i + 1;
std::sort(ndx[0], ndx[4], [&p](long i1, long i2) { comparestring((*p) + i1, (*p) + i2); })
我正在使用 VC++ 2015,上述结果导致以下错误:
Error C2893 Failed to specialize function template 'iterator_traits<_Iter>::iterator_category std::_Iter_cat(const _Iter &)'
我的 C 编程时代是古老的历史(早于 C++ 的存在),所以我有点挣扎。感谢任何帮助。
更新
代码现在看起来像这样.. 它可以编译,但执行后的顺序ndx
不正确:
long * p = (long*)pData;
long ndx[5];
for (int i = 0; i < 5; i++) ndx[i] = i + 1;
std::sort(ndx, ndx + 5, [&p](long i1, long i2) { return comparestring(*p + i1, *p + i2); })