Order container with STL member

Suppose I have some data stored in container unique_ptrs:

struct MyData {
    int id;  // a unique id for this particular instance
    data some_data; // arbitrary additional data
};

// ...

std::vector<std::unique_ptr<MyData>> my_data_vec;

Order is important my_data_vec. Suppose now that I have another MyDatas ID vector:

std::vector<int> my_data_ids;

Now I want to reorder my_data_vecso that the elements are in the sequence indicated my_data_ids. (Remember that moving a unique_ptrrequires semantics c std::move().)

What is the most algorithmically efficient way to achieve this and which of the STL algorithms is well suited to achieve this? I do not see what std::sortwill be any help.

: O (n) ( ), ( ).

+3
3
  • , my_data_ids.
  • , std::unique_ptr<MyData> ID .
  • std::sort my_data_vec .

:

// Beware, brain-compiled code ahead!
typedef std::vector<int> my_data_ids_type;
typedef std::map<int,my_data_ids_type::size_type> my_data_ids_map_type;

class my_id_comparator : public std::binary_function< bool
                                                    , std::unique_ptr<MyData>
                                                    , std::unique_ptr<MyData> > {
public:
  my_id_comparator(const my_data_ids_map_type& my_data_ids_map)
    : my_data_ids_map_(my_data_ids_map) {}

  bool operator()( const std::unique_ptr<MyData>& lhs
                 , const std::unique_ptr<MyData>& rhs ) const
  {
     my_data_ids_map_type::const_iterator it_lhs = my_data_ids_map_.find(lhs.id);
     my_data_ids_map_type::const_iterator it_rhs = my_data_ids_map_.find(rhs.id);
     if( it_lhs == my_data_ids_map_.end() || it_rhs == my_data_ids_map_.end() )
       throw "dammit!"; // whatever
     return it_lhs->second < it_rhs->second;
  }
private
  my_data_ids_map_type& my_data_ids_map_;
};

//...

my_data_ids_map_type my_data_ids_map;
// ...
// populate my_data_ids_map with the IDs and their indexes from my_data_ids
// ...
std::sort( my_data_vec.begin(), my_data_vec.end(), my_id_comparator(my_data_ids_map) );

, , my_data_ids . , , .

+3

STL? , .

0

Why don't you just use map<int, unique_ptr<MyData>>(or multimap)?

0
source

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


All Articles