我有一个二维对象数组(一个包含 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/