c++ - 将索引数组排序为主数组

标签 c++ sorting lambda import-from-excel safearray

我正在编写一个 C++ dll 来对从 VBA 传递的 SAFEARRAY 进行排序。

我没有使用任何 OLE 库,而是直接访问数组描述符和数据。

我可以毫无问题地对任何 native 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_tBSTR 非常不同,但在 Excel 字符串的有效负载中包含零字符并不常见,因此我对此表示满意。以上效果很好。

问题

我希望 dll 能够选择性地将伴随索引数组排序到主数据数组中。在这种模式下,只有索引数组会被排序,源数据保持不变。

我的研究表明,lamda 仿函数可能是最有前途的途径,因为我不希望为额外的数组或数据 vector 或对分配内存。

特别是,this answer seems very promising .

但是,我不知道如何使它适应我正在处理指向从 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); })

最佳答案

这段代码:

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); })

应该是:

long ndx[5];
for (int i = 0; i < 5; i++) ndx[i] = i;
std::sort(ndx, ndx + 5, [&](long i1, long i2) { return comparestring(*(p + i1), *(p + i2)); }

std::sort 的前两个参数是迭代器范围。使用 std::begin(ndx)std::end(ndx) 会更好(假设您的编译器与 C++11 兼容)。

另外,第二行可以写成std::iota( std::begin(ndx), std::end(ndx), 0 );

关于c++ - 将索引数组排序为主数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34053986/

相关文章:

python - 在 Python : property decorator or lambda? 中定义属性的首选方式

c++ - const static auto lambda 与引用捕获一起使用

c++ - 简单 Qt C++ 应用程序中的链接器错误

c++ - 使用另一个模板类链接一个模板类(错误 LNK2001)

c++ - 如何创建接受二维数组的构造函数

sorting - 纬度、经度坐标的比较

java - 按特定顺序对 ArrayList 中的值进行排序

c++ - 将 float 缩放到整个 unsigned int 范围

python - 按计数对 Pandas 多索引进行排序?

java - 如何将映射键值收集到列表中,其中值是集合