C++ - 按包含的对象属性对多维 vector 进行排序

标签 c++ arrays object vector sorting

我有一个二维对象数组(一个包含 GridCell 实例的二维 vector ),如下所示:

typedef vector<GridCell> CellArray;
typedef vector<CellArray> TwoDCellArray;
TwoDCellArray CellArr2D;

我目前正在像这样绘制所有单元格:

for (int i = 0; i < rows; i++){
    for (int j = 0; j < cols; j++){
        CellArr2D[i][j].draw()
    }
}

但是,我遇到了深度问题,我应该根据其大小(大小属性,CellArr2D[i][j].size)绘制实例。

我应该怎么做才能在不改变它的 i,j 值的情况下对这个数组进行排序?将所有对象复制到辅助数组并对其进行排序? 更重要的是,因此这篇文章...我如何根据包含的对象属性对数组( vector )进行排序?

提前致谢。

最佳答案

创建一个 vector 对 (i,j) 并按 size 属性对其进行排序。

typedef std::pair<int, int> int_pair_t;
typedef std::vector< int_pair_t > size_index_t;

namespace {
struct sort_helper {
    sort_helper( const TwoDCellArray& arr ) : arr_(arr) {}      
    bool operator()( const int_pair_t& ind1, const int_pair_t& ind2 ) { 
      return arr_[ind1.first][ind1.second].size > arr_[ind2.first][ind2.second].size; 
    }
private:
    const TwoDCellArray& arr_;
};

struct draw_helper {
    draw_helper( TwoDCellArray& arr ) : arr_(arr) {}        
    void operator()( const int_pair_t& ind ) { 
        arr_[ind.first][ind.second].draw();
    }
private:
    TwoDCellArray& arr_;
};
}

void some_func()
{
    // initialize helper array of indices
    size_index_t index;
    index.reserve( rows*cols );
    for ( int i = 0; i < rows*cols; ++i )
        index.push_back( make_pair( i/cols%rows, i%cols ) );

    // sort according to the `size` field
    std::sort( index.begin(), index.end(), sort_helper( CellArr2D ) );

    // draw
    std::for_each( index.begin(), index.end(), draw_helper( CellArr2D ) );
}

关于C++ - 按包含的对象属性对多维 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413686/

相关文章:

javascript循环嵌套数组并根据另一个数组提取属性

ios - 从 UITableViewCell 更新 UIViewController 中数组的对象

arrays - 找到具有给定约束的最大总和的对

ruby - 如何在 Ruby 中通过分隔符拆分数组?

javascript - 有没有办法在 JavaScript 中遍历可能自包含的对象?

javascript - 关于继承我不明白的几件事

c++ - 有没有办法从变量设置模板参数?

C++ 指针数组

c++ - 具有多个 WSDL 的 gSoap

c++ - 找不到 PDB 'vc100.pdb'