【问题标题】:C++ operating on "packed" arraysC++ 在“打包”数组上运行
【发布时间】:2023-03-08 21:01:01
【问题描述】:

假设我有两个,例如float 数组ab,一个int 键数组k 和一个我自己的模板mySortByKey 函数,对单个数组进行操作,像

template<class T>
mySortByKey(int *k, T *a)

是否有可能(例如,使用 zip 迭代器和某种类型的元组)启用 mySort 同时在 ab 上运行,以便它们可以根据键 k 同时进行排序?

【问题讨论】:

    标签: c++ arrays templates iterator tuples


    【解决方案1】:

    我认为你做不到。但是,您可以通过使用索引辅助数组来完成类似的操作。

    int keys[ARRAY_SIZE];
    float a[ARRAY_SIZE];
    float b[ARRAY_SIZE];
    
    // Fill up the contents of keys, a, and b
    
    // Create an array of indices.
    int indices[ARRAY_SIZE];
    for ( int i = 0; i < ARRAY_SIZE; ++i )
       indices[i] = i;
    
    // Sort the indices using keys.
    mySortByKey(keys, indices);
    
    // Now access the arrays a and b indirectly, using the sorted array
    // of indices as an intermediate object.
    for ( int i = 0; i < ARRAY_SIZE; ++i )
    {
       float fa = a[indices[i]];
       float fb = b[indices[i]];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多