C ++ - Sorting a multidimensional vector by its contained object

I have a two-dimensional array of objects (a 2D vector containing GridCell instances), like here:

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

I am currently drawing all cells as follows:

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

However, I have a problem with depth, and I have to draw instances depending on its size (size property, CellArr2D [i] [j] .size).

What should I do to sort this array without changing its i, j values? Copying all objects to a secondary array and sorting this? And more importantly, therefore, this post ... how can I sort an array (vector) using this object property?

Thanks in advance.

+3
source share
3 answers

(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 ) );
}
+3

std:: sort .

, , , , . - GridCells . , .

+1

You can put the links in a secondary array and sort it:

struct CellRef
{
  CellRef(GridCell& cell) : m_c(cell) {}
  bool operator<(const CellRef& r) const { return m_c.size < r.m_c.size; }
  GridCell& data() { return m_c; }
private:
  GridCell& m_c;
};

vector<CellRef> refs;
for (int i = 0; i < rows; i++){
    for (int j = 0; j < cols; j++){
        refs.push_back(CellArr2D[i][j]);
    }
}
std::sort(refs.begin(), refs.end());
for(vector<CellRef>::iterator it=refs.begin(), end=refs.end(); it!=end; ++it)
  it->data().draw();
0
source

Source: https://habr.com/ru/post/1758182/


All Articles